簡體   English   中英

SQL計數另一個表中的行並聯接

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM