[SOLVED] SQL: How to join two tables and extract the data by timestamp?

Issue

This Content is from Stack Overflow. Question asked by amber_the_debutant

I’m using mysql. I have two tables, one is about movie type, and the other is about movie rating with timestamps. I want to join these two tables together with movie id to count the average rating for each type of movie. I’m trying to extract only the movie types which have at least 10 ratings per film and the ratings made in December, and order by the highest to lowest average rating.

Table ‘types’

movieIdtype
1Drama
2Adventure
3Comedy

Table ‘ratings’

movieIdratingtimestamp
11851786086
21.51114306148
121228946388
32850723898
12.51167422234
22.51291654669
13851345204
23944978286
33965088579
331012598088
13.51291598726
141291779829
14850021197
24945362514
14.51072836909
15881166397
15944892273
251012598088

Expect result: (Nb ratings >= 10 and rate given in December)
| type | Avg_Rating |
| ——- | ———- |
| Drama | 3.45 |


I’m trying to write the query like below, but I’m not able to execute it. (around 10 thousand data in original table)
Where should I adjust my query?

SELECT DISTINCT T.type, AVG(R.rating) FROM types AS T
INNER JOIN ratings AS R ON T.movieId = R.movieId
WHERE R.timestamp LIKE (
    SELECT FROM_UNIXTIME(R.timestamp,'%M') AS Month FROM ratings
    GROUP BY Month
    HAVING Month = 'December')
GROUP BY T.type
HAVING COUNT(R.rating) >=10
ORDER BY AVG(R.rating) DESC;



Solution

You can try next query.

SELECT DISTINCT T.type, AVG(R.rating) FROM types AS T
INNER JOIN ratings AS R ON T.movieId = R.movieId
GROUP BY T.type
HAVING 
    COUNT(R.rating) >= 10 -- have 10 or more rating records
    AND SUM(MONTH(FROM_UNIXTIME(R.timestamp)) = 12) > 0 -- have at least one rating in December
ORDER BY AVG(R.rating) DESC;

sqlize


This Question was asked in StackOverflow by amber_the_debutant and Answered by Slava Rozhnev It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?