MySQL - 添加列并显示每条记录

时间:2017-01-31 03:40:36

标签: mysql sum left-join

我有这个查询

select articles.articleID, user_votes.tagID, user_votes.count from  articles 
left join article_tags on article_tags.articleID = articles.articleID
inner join user_votes on user_votes.tagID = article_tags.tagID

并返回以下内容

"articleID" "tagID" "count"
    "1"       "1"     "2"
    "1"       "2"    "-5"
    "1"       "3"     "7"
    "2"       "1"     "2"
    "3"       "1"     "2"
    "4"       "1"     "2"
    "6"       "1"     "2"
    "7"       "1"     "2"

我希望能够让它返回到它所说的articleID的位置,然后为该文章的每个tagID添加计数。

因此,它不会显示3次文章ID,3个标记和3个值,而是显示

"1", "this doesn't matter", "4" 
"2", "...", "2"
"3". "...", "2"

我尝试使用总和,我尝试使用案例,但我永远无法让它工作。

我试过了:

select articles.articleID, SUM(user_votes.count) as totalScore from articles 
left join article_tags on article_tags.articleID = articles.articleID
left join user_votes on user_votes.tagID = article_tags.tagID

然后返回

articleID, totalScore
    1          452 

每篇文章的每个计数都加起来。

希望这很有意义并且很容易解决。我很困惑!

提前致谢。 罗布

1 个答案:

答案 0 :(得分:1)

添加缺失的.visually-hidden { position: absolute !important; clip: rect(1px 1px 1px 1px); /* IE6, IE7 */ clip: rect(1px, 1px, 1px, 1px); padding:0 !important; border:0 !important; height: 1px !important; width: 1px !important; overflow: hidden; }

group by

此外,尝试使用别名,这样可以避免在任何地方输入完整的表名。

select articles.articleID, SUM(user_votes.count) as totalScore from articles 
left join article_tags on article_tags.articleID = articles.articleID
left join user_votes on user_votes.tagID = article_tags.tagID
group by articles.articleID; -- here