我有2个表:用户和评论,一对多的关系。
当我执行以下查询时:
SELECT
user_id,
count(*) totalReviews,
USER . NAME
FROM
review,
USER
WHERE
USER .id = review.user_id
GROUP BY
user_id
我明白了:
1 2 marius
2 2 daniela
3 1 alin
我现在要做的是显示前2位用户,因为他们给出了最多的评论(2)。
我尝试添加,如果我硬编码having totalReviews=2
它有效,但如果我写having total = max(total)
我得到0结果,而如果我尝试,
SELECT
*
FROM
(
SELECT
user_id,
count(*) total,
USER . NAME
FROM
review,
USER
WHERE
USER .id = review.user_id
GROUP BY
user_id
) A
WHERE
total = (SELECT max(total) FROM A) `
我收到错误(表格A不存在)
答案 0 :(得分:2)
您可以使用ORDER BY
和LIMIT
执行此操作:
SELECT u.id, count(*) as totalReviews, u.name
FROM review r JOIN
user u
ON u.id = r.user_id
GROUP BY u.id, u.name
ORDER BY totalReviews DESC
LIMIT 2;
注意:
FROM
子句中使用逗号。 始终使用正确的JOIN
语法。编辑:
如果我发现您希望所有用户都拥有最多的评论数,而不是2。这是一种方法:
SELECT u.id, COUNT(*) as totalReviews, u.name
FROM review r JOIN
user u
ON u.id = r.user_id
GROUP BY u.id, u.name
HAVING totalReviews = (SELECT COUNT(*)
FROM review r2
GROUP BY r2.user_id
ORDER BY COUNT(*) DESC
LIMIT 1
);
请注意,HAVING
子句中的子查询比外部查询简单。无需引入用户名。