I have two tables. One is books table. It has two columns. id|title. Another is student_books table. It has two columns student_id|book_id. When a student tries to read a book, I check the student_books table whether the student_id and the book_id matches or not. A student can buy multiple books so there may have multiple entries in student_books table. now I want to show the list of books based on popularity(that has maximum entries in student_books table) on a page. How should I write the SQL query?
-
Can you provide the query that you have tried to write to get the data you want? What is your intended output of the query? Just the book titles ordered by popularity? or the actual count?Tah– Tah2017-01-04 04:02:37 +00:00Commented Jan 4, 2017 at 4:02
Add a comment
|
2 Answers
SELECT b.id, b.title
FROM books b
LEFT JOIN students s ON s.book_id = b.id
GROUP BY b.id, b.title
ORDER BY COUNT(s.book_id) DESC;
5 Comments
Tim Biegeleisen
You are selecting
title but this column is not aggregate and also does not appear in the GROUP BY.shmosel
@TimBiegeleisen Not a problem in MySQL.
Tim Biegeleisen
Yes, it is a problem in MySQL, and your query would not run in certain versions.
shmosel
@TimBiegeleisen Do you have a source or example?
Tim Biegeleisen
dev.mysql.com/doc/refman/5.7/en/… ...
As of MySQL 5.7.5, the default SQL mode includes ONLY_FULL_GROUP_BY.