sql - 如何从表中加入 COUNT,然后用另一个 JOIN 影响该 COUNT

标签 sql join count

我有三张 table

邮政

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          

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

我可以从 Post 中选择数据,然后从 Comment Fine 中加入一个计数。但是这个计数应该取决于配置文件是否被批准。

我期待的结果是

评论数
PostId  Count
1       1
2       0
3       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

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

关于sql - 如何从表中加入 COUNT,然后用另一个 JOIN 影响该 COUNT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2613005/

相关文章:

sql - 用于提高 SQL Server 上多个连接性能的索引 View

sql - 获取给定日期之间的所有日期

MySQL表链接1 :n

MYSQL join子查询使用count(*)查找用户拥有的关系数

mysql - 将事件表与 MYSQL 中的源表连接

SQL 查询 - 计数 - 最大值

arrays - 当没有频繁值时如何处理数组中的频繁值

mysql - SQL 查询多次返回 group_concat 函数中的标签字段

sql - 如何在Linux/Grails/Groovy环境中的Grails h2数据源中 “look at data”?

SQL聚合函数子查询