我尝试从表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 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=1
Nader Gharibian Fard
https://stackoverflow.com/questions/64841208
复制相似问题