I have a table
movies
movie_id
movie_name
language
cast
ratings
id
movie_id
rating
comment
I need to fetch all movies details with average and total count of ratings.
If there is no rating for any movie, average rating and total ratings count must be zero.
for this i tried this MySQL query:
SELECT m.movie_id,movie_name,cast,language,AVG(rating) as average_rating,COUNT(rating) as total_rating
FROM movies m
LEFT JOIN ratings r ON m.movie_id=r.movie_id;
But this query not giving all movies lists from 'movies' table.
Please help. Thank you.
Use group by
with movie_id
so it will differentiate your result with unique movie_id.
SELECT m.movie_id,m.movie_name,m.cast,m.language,AVG(r.rating) as average_rating,COUNT(r.rating) as total_rating
FROM movies m
LEFT JOIN ratings r ON m.movie_id=r.movie_id
GROUP BY m.movie_id;
You need to add GROUP BY m.movie_id
SELECT
`m`.`movie_id`, `m`.`movie_name`, `m`.`cast`, `m`.`language`,
AVG(`r`.`rating`) `average_rating`, COUNT(`r`.`rating`) `total_rating`
FROM
`movies` `m`
LEFT JOIN
`ratings` `r`
ON
`m`.`movie_id` = `r`.`movie_id`
GROUP BY
`m`.`movie_id`;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.