gpt4 book ai didi

mysql - 多重连接和分组

转载 作者:行者123 更新时间:2023-11-29 03:32:22 24 4
gpt4 key购买 nike

我尝试创建一个 View 的三个表。这三个表是,

新闻

---------|---------|
newsID | title |
---------|---------|
1 | title1 |
2 | title2 |
3 | title3 |
---------|---------|

评论

-----------|----------|-----------|
commentID | newsID | comment |
-----------|----------|-----------|
1 | 1 | |
2 | 1 | |
3 | 1 | |
4 | 1 | |
5 | 2 | |
-----------|----------|-----------|

投票

-----------|----------|------|
voteID | newsID | vote |
-----------|----------|------|
1 | 1 | 5 |
2 | 2 | 4 |
3 | 1 | 5 |
-----------|----------|------|

我的查询是

SELECT  news.newsID,  SUM(votes.vote) AS total,COUNT(comments.commentID) AS comment_count 
FROM news
LEFT JOIN votes ON news.newsID = votes.newsID
LEFT JOIN comments ON news.newsID = comments.newsID
GROUP BY newsID

这个查询的结果

-----------|----------|---------------|
newsID | total | comment_count |
-----------|----------|---------------|
1 | 40 | 8 |
2 | 4 | 1 |
3 | null | 0 |
-----------|----------|---------------|

但应该是这样的

-----------|----------|---------------|
newsID | total | comment_count |
-----------|----------|---------------|
1 | 10 | 4 |
2 | 4 | 1 |
3 | null | 0 |
-----------|----------|---------------|

我将使用此查询来创建 View ,因此我不能使用子查询。我该如何解决这个问题?

最佳答案

执行这个查询:

    SELECT news.newsID, (SELECT SUM(votes.vote) FROM votes WHERE votes.newsID = news.newsID) AS total, (SELECT COUNT(comments.commentID)FROM comments WHERE comments.newsID = news.newsID) AS comment_count
FROM news
GROUP BY newsID

关于mysql - 多重连接和分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28712572/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com