我有这个SQL查询来获取租用某些类别书籍的次数。
SELECT Category.name, COUNT(*) AS "times rented"
FROM Category
INNER JOIN Book ON Book.category=Category.name
INNER JOIN Rent ON Rent.book_id=Book.id
GROUP BY Category.name
ORDER BY COUNT(*) DESC
LIMIT 1
如果我想获得最受欢迎的书,现在这将完美地运作。问题在于“限制1”。我有多本书,与上面的查询结果一样多次租用。删除“LIMIT 1”只会返回所有租借的类别。
假设上面的查询返回此
name | times rented
Adventure 153
Comics 153
Biography 102
Romance 80
如何同时返回“冒险”和“漫画”?
答案 0 :(得分:1)
您可以使用MAX()。
SELECT Category.name, COUNT(*) times_rented
FROM Category
INNER JOIN Book ON Book.category=Category.name
INNER JOIN Rent ON Rent.book_id=Book.id
INNER JOIN (select MAX(COUNT(*)) max_count FROM Category GROUP BY Category.name) t ON t.id = Category.id AND Category.times_rented = t.max_count
GROUP BY Category.name
答案 1 :(得分:1)
您可以使用最大计数进行比较,并将"
替换为backticks
中的times rented
,将其用作别名而不发出警告。
SELECT Category.name, COUNT(*) AS `times rented`
FROM Category
INNER JOIN Book ON Book.category=Category.name
INNER JOIN Rent ON Rent.book_id=Book.id
GROUP BY Category.name
having `times rented` = (select MAX(cnt) from
(select COUNT(*) as cnt FROM Category GROUP BY Category.name) temp
)