我有一个论坛,我想找到最受欢迎的用户。最受欢迎的用户由对帖子和评论的最多点赞定义,也由最多的帖子和评论定义。喜欢最多(顺序 1)、帖子最多(顺序 2)和评论最多(顺序 3)的用户最受欢迎。同样的逻辑适用于下一个(第二个)最受欢迎的用户。
所以我有3张桌子:
帖子表
id user_id likes
1 1 0
2 1 0
3 1 0
4 1 0
5 1 0
6 1 1
7 1 0
8 2 0
9 2 2
10 2 0
11 2 0
12 3 0
13 3 0
14 4 0
15 4 10
评论表
id user_id likes
1 1 0
2 1 1
3 1 1
4 1 0
5 2 0
6 2 2
7 2 1
8 4 1
9 4 0
用户表
id name
1 John
2 Adam
3 Maggie
4 Steve
喜欢列包含其他用户在相应帖子(行)上给出的喜欢。我试过了:
SELECT DISTINCT c.id, c.name,
SUM(a.likes), SUM(b.likes), (SUM(a.likes) + SUM(b.likes)) as popular,
COUNT(a.id) as mostp, COUNT(b.id) as mostc
FROM posts as a, comments as b, users as c
WHERE a.user_id=b.user_id AND a.user_id=c.id AND b.user_id=c.id
GROUP BY a.user_id, b.user_id ORDER BY popular DESC, mostp DESC, mostc DESC
显然,这不起作用,因为如果您测试查询,它会给出比预期更多的喜欢(总和)。