[英]How to join COUNT(*) from another JOINed table
我有 3 个数据库: Users
、 Posts
、 Comments
。
我想执行一个获取所有帖子信息的查询
SELECT
Posts.id as postId,
Users.id as authorId,
Posts.title,
Users.displayName,
Posts.createdAt
FROM
Users
INNER JOIN
Posts
ON
Users.id = Posts.authorId;
返回类似的东西
+--------+----------+---------+-------------+---------------------+
| postId | authorId | title | displayName | createdAt |
+--------+----------+---------+-------------+---------------------+
| 1 | 1 | title 1 | Alice | 2022-07-22 16:35:39 |
| 2 | 2 | title 2 | Bob | 2022-07-22 16:35:47 |
+--------+----------+---------+-------------+---------------------+
我想加入这个结果
SELECT postId, COUNT(*) FROM Comments GROUP BY postId
它返回类似的东西
+--------+----------+
| postId | COUNT(*) |
+--------+----------+
| 1 | 5 |
| 2 | 3 |
+--------+----------+
我想要达到的最终结果是
+--------+----------+---------+-------------+---------------------+--------------+
| postId | authorId | title | displayName | createdAt | commentCount |
+--------+----------+---------+-------------+---------------------+--------------+
| 1 | 1 | title 1 | Alice | 2022-07-22 16:35:39 | 5 |
| 2 | 2 | title 2 | Bob | 2022-07-22 16:35:47 | 3 |
+--------+----------+---------+-------------+---------------------+--------------+
我应该如何编写 SQL 查询? (我正在使用 MySQL)
你有 3 张桌子(?),你可以试试这个:
SELECT
P.ID AS POSTID,
U.ID AS AUTHORID,
P.TITLE,
U.DISPLAYNAME,
P.CREATEDAT,
C.CNT
FROM
USERS U
INNER JOIN
POSTS P
ON
U.ID = P.AUTHORID
JOIN (SELECT POSTID, COUNT(*) CNT FROM COMMENTS GROUP BY POSTID) C
ON C.POSTID = P.ID;
您可以使用子查询(“标量子查询”)来获取每个帖子的评论数。
例如:
SELECT
p.id as postId,
u.id as authorId,
p.title,
u.displayName,
p.createdAt,
(select count(*) from comments c where c.postid = p.id) as comment_count
FROM
Users u
INNER JOIN
Posts p
ON
u.id = p.authorId;
我在表格中添加了别名以提高可读性。
您可以在此处使用 CTE(通用表表达式)。 以下是查询:
with comment_count as
(
SELECT postId, COUNT(*) as commentCount FROM Comments GROUP BY postId
),
post_processed as
(
SELECT
Posts.id as postId,
Users.id as authorId,
Posts.title,
Users.displayName,
Posts.createdAt
FROM
Users,
Posts
where
Users.id = Posts.authorId
)
select
pp.*,
cc.commentCount
from
post_processed pp,
comment_count cc
where pp.postId = cc.postId;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.