简体   繁体   English

如何计算左连接中的另一个表

[英]How to get count of another table in a left join

I have multiple tables 我有多个表

post
    id  Name
    1   post-name1
    2   post-name2

user
    id  username
    1   user1
    2   user2

post_user
    post_id   user_id
    1         1
    2         1

post_comments
    post_id   comment_id
    1         1
    1         2
    1         3

I am using a query like this: 我正在使用这样的查询:

SELECT post.id, post.title, user.id AS uid, username
FROM `post`
LEFT JOIN post_user ON post.id = post_user.post_id
LEFT JOIN user ON user.id = post_user.user_id
ORDER BY post_date DESC

It works as intended. 它按预期工作。 However I would like the get the number of comments for each post too. 但是,我想获得每个帖子的评论数量。 So how can i modify the this query so I can get the count of comments. 那么如何修改此查询以便我可以获得评论的数量。

Any ideas? 有任何想法吗?

SELECT post.id, post.title, user.id AS uid, username, COALESCE(x.cnt,0) AS comment_count
FROM `post`
LEFT JOIN post_user ON post.id = post_user.post_id
LEFT JOIN user ON user.id = post_user.user_id
LEFT OUTER JOIN (SELECT post_id, count(*) cnt FROM post_comments GROUP BY post_id) x ON post.id = x.post_id
ORDER BY post_date DESC

EDIT: made it an outer join in case there aren't any comments 编辑:如果没有任何评论,使其成为外部联接

EDIT2: Changed IsNull to Coalesce EDIT2:将IsNull更改为Coalesce

This edited version shows rows with no comments: 此编辑版本显示没有注释的行:

SELECT post.id, post.title, user.id AS uid, username, count(post_comments.comment_id) as comment_count
FROM `post`
LEFT JOIN post_user ON post.id = post_user.post_id
LEFT JOIN user ON user.id = post_user.user_id
LEFT JOIN post_comments ON post_comments.post_id = post.id
GROUP BY post.id
ORDER BY post_date DESC

For example: 例如:

+----+------------+------+----------+---------------+
| id | title      | uid  | username | comment_count |
+----+------------+------+----------+---------------+
|  3 | post-name3 |    2 | user2    |             0 | 
|  1 | post-name1 |    1 | user1    |             3 | 
|  2 | post-name2 |    1 | user1    |             1 | 
+----+------------+------+----------+---------------+
3 rows in set (0.01 sec)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM