我尝试从表1 (posts)的单个行返回字段,并将该post的第二个表( comments )中出现的评论数连接到此行。
但是,它从不返回count值。
SELECT posts.post_title, posts.post_author, posts.post_date, posts.post_article
FROM posts LEFT OUTER JOIN (SELECT COUNT(*) FROM comments WHERE comments.comment_post_id = 25) AS comments
ON posts.post_id = comments.comment_post_id WHERE post_id = 25; 我知道我可能错过了一些简单的东西,但我已经在这上面花了太多的时间,所以我想我应该寻求帮助。由于我是SQL的新手,我非常感谢您的解释以及任何代码更改建议。
发布于 2020-11-15 20:55:42
我建议使用相关子查询:
SELECT p.post_title, p.post_author, p.post_date, p.post_article,
(SELECT COUNT(*)
FROM comments c
WHERE c.comment_post_id = p.post_id
) as num_comments
FROM posts p
WHERE p.post_id = 25;这有效地允许您在查询中只有一次25 --减少了编码错误的范围。
您的代码无法工作,因为您没有选择外部SELECT中的count列。记住: SQL查询描述的是结果集。如果SELECT中没有列或表达式,则不会选择它。
发布于 2020-11-15 12:37:51
您不需要外连接,因为count si查询只有一行。假设您想这样做,那么在您的子查询中包含post_id。
SELECT posts.post_title, posts.post_author, posts.post_date, posts.post_article, ncomments
FROM posts LEFT OUTER JOIN (SELECT post_id, COUNT(*) as ncomments FROM comments WHERE comments.comment_post_id = 25) AS comments
ON posts.post_id = comments.comment_post_id WHERE post_id = 25; 否则,我认为应该这样做:
但是,它从不返回count值。
SELECT posts.post_title, posts.post_author, posts.post_date, posts.post_article, ncomments
FROM posts INNER JOIN (SELECT COUNT(*) AS ncomments FROM comments WHERE comments.comment_post_id = 25) AS comments发布于 2020-11-15 13:09:59
解决这个问题的两种方法..
一种快速的解决方案..
SELECT posts.post_title, posts.post_author, posts.post_date, posts.post_article,(SELECT COUNT(*) FROM comments WHERE comments.comment_post_id = posts.comment_post_id)CountComment
FROM posts post
WHERE post_id = 25;最好的解决方案..
select mainQueryPosts.post_title, mainQueryPosts.post_author, mainQueryPosts.post_date, mainQueryPosts.post_article,mainQueryPosts.count,mainQueryPosts.rownumber
from (
SELECT posts.post_title, posts.post_author, posts.post_date, posts.post_article,count(*) over (partition by comments.comment_post_id) count, ROW_NUMBER() OVER (partition by comments.comment_post_id ORDER BY comments.CreateDate) rownumber
FROM posts inner join comments on comments.comment_post_id = post.comment_post_id
WHERE post_id = 25
) mainQueryPosts
where mainQueryPosts.rownumber=1Nader Gharibian Fard
https://stackoverflow.com/questions/64841208
复制相似问题