Reputation: 289
I have two tables: Anime_List and Anime_Reviews.
Anime_List table has a 'Rating' field that grabs the average rating from Anime_Reviews. However, some ratings (rows) don't exist in Anime_Reviews and so my current query only returns titles that have a average rating.
SELECT Anime_List.AnimeID, Anime_List.Name, Anime_List.AnimeImage, Anime_List.Synopsis, Anime_List.Type, Anime_List.Episodes, Anime_List.Genres, AVG(Anime_Reviews.Rating)
FROM Anime_List INNER JOIN Anime_Reviews ON Anime_List.AnimeID = Anime_Reviews.AnimeID
GROUP BY Anime_List.AnimeID, Anime_List.Name, Anime_List.AnimeImage, Anime_List.Synopsis, Anime_List.Type, Anime_List.Episodes, Anime_List.Genres
How do I return the value of 0.0 if there are no ratings (rows) in Anime_Reviews for each title listed in Anime_List?
Upvotes: 1
Views: 1218
Reputation: 79929
Use LEFT JOIN
with COALESCE
:
SELECT
l.AnimeID,
l.Name,
l.AnimeImage,
l.Synopsis,
l.Type,
l.Episodes,
l.Genres,
COALESCE(AVG(r.Rating), 0) AS Rating
FROM Anime_List AS l
LEFT JOIN Anime_Reviews AS r ON l.AnimeID = r.AnimeID
GROUP BY l.AnimeID,
l.Name,
l.AnimeImage,
l.Synopsis,
l.Type,
l.Episodes,
l.Genres;
For more information about the different types of SQL JOIN
see this article please:
Upvotes: 2
Reputation: 92785
A version using a subquery
SELECT l.AnimeID,
l.Name,
l.AnimeImage,
l.Synopsis,
l.Type,
l.Episodes,
l.Genres,
(SELECT ISNULL(AVG(Rating), 0) Rating
FROM Anime_Reviews
WHERE AnimeID = l.AnimeID)
FROM Anime_List l
Upvotes: 5