【问题标题】:How to JOIN a COUNT from a table, and then effect that COUNT with another JOIN如何从表中加入一个 COUNT,然后用另一个 JOIN 影响该 COUNT
【发布时间】:2011-02-06 11:12:13
【问题描述】:

我有三张桌子

发帖

ID  Name
1   'Something'
2   'Something else'
3   'One more'

评论

ID  PostId  ProfileID  Comment
1   1       1          'Hi my name is' 
2   2       2          'I like cakes'
3   3       3          'I hate cakes'

简介

ID  Approved
1   1          
2   0          
3   1          

我想计算评论个人资料已获批准的帖子的 cmets

我可以从 Post 中选择数据,然后从 Comment 中加入计数。但是这个计数应该取决于个人资料是否被批准。

我期待的结果是

评论数

PostId  Count
1       1
2       0
3       1

【问题讨论】:

  • Profile 表 1-1 和Comment 是一个吗?
  • 不,个人资料可以发表很多评论。

标签: sql join count


【解决方案1】:

您可以像这样使用嵌套选择:

SELECT Post.Id, temp.Count
FROM Post
LEFT JOIN
(SELECT Post.Id, COUNT(Comment.ID) AS Count
FROM Post
LEFT JOIN Comment ON Comment.PostId = Post.ID
LEFT JOIN Profile ON Profile.ID = Comment.ProfileID
WHERE Profile.Approved = 1
GROUP BY Post.Id)
temp ON temp.Id = Post.ID

如果没有帖子,而不是没有记录,这会给你 null:

1  1
2  null
3  1

为了改善这一点,您可以使用 if 来摆脱空值

SELECT Post.Id, if(temp.Count >= 1,temp.Count,0) as newCount
FROM Post
LEFT JOIN
(SELECT Post.Id, COUNT(Comment.ID) AS Count
FROM Post
LEFT JOIN Comment ON Comment.PostId = Post.ID
LEFT JOIN Profile ON Profile.ID = Comment.ProfileID
WHERE Profile.Approved = 1
GROUP BY Post.Id) temp ON temp.Id = Post.ID

这给了你最初想要的东西:

1  1
2  0
3  1

注意:很可能有一个更优雅的解决方案!!!!

【讨论】:

    【解决方案2】:

    从COUNT函数的定义来看:

    COUNT 函数只会计数 字段所在的那些记录 括号不为空。

    这意味着像这样的简单外连接可以工作:

    SELECT Post.ID, COUNT(Comment.ID)
      FROM Post LEFT JOIN Comment ON (Post.ID = Comment.PostId)
                LEFT JOIN Profile ON (Profile.ID = Comment.ProfileID AND
                                      Profile.Approved = 1)
     GROUP BY Post.ID
    

    【讨论】:

    • 这也不起作用,它只返回两行。即使COUNT 为空,我也需要返回所有行。
    • 对不起,当然不是 - 看看我如何在 Profile.Approved 上移动条件来修复它...
    【解决方案3】:
    SELECT Post.Id, COUNT(Comment.ID) AS Count
    FROM Post
    LEFT JOIN Comment ON Comment.PostId = Post.ID
    LEFT JOIN Profile ON Profile.ID = Comment.ProfileID
    WHERE Profile.Approved = 1
    GROUP BY Post.Id
    

    可能您没有为了示例而粘贴它,但您可能会通过移动其中的 Approved 列来评估 Profile 表和 Comment 表一起去规范化。

    【讨论】:

    • 这是个好主意!虽然这意味着需要更多的编码来确保表格在配置文件被批准和暂停时保持最新。另外,如何让表名在评论中显示为内联代码?
    • 这给了我正确的计数,但仅适用于拥有CommentsPosts。即使他们没有任何 cmets,我也需要返回所有 Posts 及其计数。很抱歉我一开始没有说清楚。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-18
    • 1970-01-01
    相关资源
    最近更新 更多