我有3张桌子
表新闻:
id_post | news | id_user
3 | IT news | 1
4 | game news | 2
表用户:
id_user | username
1 | bocah
2 | gundul
3 | ganteng
和表投票
id_vote | id_post | id_user | LIKE
10 | 3 | 2 | 1
11 | 3 | 3 | 1
12 | 3 | 1 | 1
这是我的SQL查询:
SELECT id_vote, u.id, username, SUM(v.like) AS like FROM vote v
LEFT JOIN user u ON v.id_user=u.id
LEFT JOIN post p ON v.id_post=p.id_post
WHERE YEARWEEK(p.time)=YEARWEEK(NOW())
GROUP BY u.id ORDER BY like DESC LIMIT 4
我想显示最新用户总数,例如本周新闻的位置。在我的期望用户1中,bocah将显示 3 LIKE 。问题是用户1,bocah,只收到1个LIKE。
任何答案?
答案 0 :(得分:0)
尝试以下查询。它应该按照您的期望工作。
SELECT u.id_user, u.username, SUM(v.like) AS like
FROM USER u
LEFT JOIN news n ON u.id_user=n.id_user
LEFT JOIN vote v ON v.id_post=n.id_post
WHERE YEARWEEK(v.time)=YEARWEEK(NOW())
GROUP BY u.id_user
答案 1 :(得分:0)
从投票表中删除id_user列。 (冲突,你在投票表中显示用户2的不同帖子。) 然后像这样进行查询,我猜它会对你有帮助。
select sum(`likes`) as `Like`, user.user_id , user.id_user from vote v
LEFT JOIN news n ON v.id_post=n.id_post
LEFT JOIN user u ON n.id_user=u.id_user
where <your time condition>
group by v.id_post
order by `like` desc limit 4
答案 2 :(得分:0)
试试这个:
SELECT
n.*,
u.`username`,
(SELECT SUM(`like`) FROM vote WHERE id_post = n.`id_post` ) AS likes
FROM news n
INNER JOIN `user` u ON u.`id_user` = n.`id_user`
WHERE YEARWEEK(n.time)=YEARWEEK(NOW())
ORDER BY likes DESC LIMIT 4;
从表格中我可以看到,你希望每个新闻帖的最高票数赞成吗? 我假设日期时间字段在新闻表中,还是在投票完成时?
结果:
id_post |news |id_user | username | likes
3 | IT News |1 | gandul |3 4 |game news |2 | bocah |(NULL)