我有users
表,我有posts
表我希望从users
表中选择来自posts
表的大量帖子的顶级用户,并按顺序排序帖子数量
我可以通过array_count_values()
来订购它
现在我想如果我通过左边的一个mysql查询来做它并且join会更好
表格结构
posts
id | auther_id
我试过这个
SELECT COUNT(1) cnt, u.user_id
FROM users u
LEFT JOIN posts p
ON p.author_id=u.user_id
GROUP BY u.user_id
ORDER BY cnt DESC
LIMIT 20
答案 0 :(得分:5)
您需要使用GROUP BY u.user_id按用户聚合帖子,按降序获取帖子数量和ORDER BY该数字的COUNT值:
SELECT COUNT(1) cnt, u.user_id
FROM users u
LEFT JOIN posts p
ON p.author_id=u.user_id
GROUP BY u.user_id
ORDER BY cnt DESC
LIMIT 20
答案 1 :(得分:2)
SELECT u.user_id, COUNT(*) as post_count
FROM users u
INNER JOIN posts p
USING (user_id)
GROUP BY u.user_id
ORDER BY post_count
答案 2 :(得分:0)
我用过这个并且它起作用了 这是真的
SELECT COUNT( 1 ) cnt, a.auther_id
FROM `posts` a
LEFT JOIN users u ON a.auther_id = u.id
GROUP BY a.auther_id
ORDER BY cnt DESC
LIMIT 20