[英]SQL Count rows in another table and join
我的数据库中有2个表。 第一个是comments
,另一个是comments_votes
。 我要选择所有评论,并为每个评论从comments_votes
选择所有投票,将它们加在一起,并与第一个查询一起加入totalVote。
我的comments
表如下:
id comment video_id date_sent
----------------------------------------
5 "...." 99 "2017-05-23"
18 "...." 99 "2017-05-23"
comments_votes
表如下所示:
id user_id comment_id vote
----------------------------------------
45 86 5 1
45 23 5 1
78 12 18 -1
最终希望的结果如下所示:
id comment video_id votes_total
----------------------------------------
5 " ... " 99 2
18 "... " 99 -1
我可以管理简单的SQL操作,但这超出了我的范围。 这样的事情可能吗? 如果是,怎么办?
select C.id, C.Comment, C.Video_ID, SUM(V.Votes) AS Vote_total
from comments C
left outer join comments_votes V
on C.id=V.comment_id
group by C.id, C.Comment, C.Video_ID
SELECT c.id,comment,c.video_id,SUM(v.vote) AS Vote_total
FROM comments c, comments_votes v
WHERE c.id = v.comment_id
GROUP BY C.id, C.Comment, C.Video_ID;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.