简体   繁体   English

SQL计数另一个表中的行并联接

[英]SQL Count rows in another table and join

I have 2 table in my database. 我的数据库中有2个表。 The first is comments and the other is comments_votes . 第一个是comments ,另一个是comments_votes I want to select all comments, and for each comment, select all it's votes from comments_votes , add them up together and join it with the first query as totalVote. 我要选择所有评论,并为每个评论从comments_votes选择所有投票,将它们加在一起,并与第一个查询一起加入totalVote。

My comments table look like: 我的comments表如下:

id      comment      video_id   date_sent
----------------------------------------
5      "...."           99        "2017-05-23"
18      "...."          99        "2017-05-23"

comments_votes table look like: comments_votes表如下所示:

id      user_id      comment_id   vote
----------------------------------------
45         86           5         1
45         23           5         1
78         12            18        -1 

And the final wished result would look like: 最终希望的结果如下所示:

id      comment   video_id   votes_total
----------------------------------------
5      " ... "      99             2
18      "... "      99           -1

I can manage simple SQL operations but this is beyond me. 我可以管理简单的SQL操作,但这超出了我的范围。 Is something like this even possible? 这样的事情可能吗? If yes, how? 如果是,怎么办?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM