Answer the question
In order to leave comments, you need to log in
How to write such a SQL query (details inside)?
Hello.
I have books. And their rating. The books in the books table. The rating is in books_rating. The problem is in the arrangement of the books_rating table. There are such fields:
id, book_id, user_id, rating (1 and -1).
That is, entries appear only when the user has rated the book. If it cancels its rating, then the entry is deleted.
How do I write a SQL query that returns all fields from the books table. And calculates the rating for each book - COUNT of records from the books_rating table. Records where the book_id field is equal to the id from the book table. Well, if there are no records for this book in books_rating, then 0.
Answer the question
In order to leave comments, you need to log in
ranking for each book - COUNT of records
SELECT b.*, COALESCE(SUM(br.rating), 0) rating
FROM books b
LEFT JOIN books_rating br ON br.book_id = b.id
GROUP BY b.id
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question