如下设置有效。
但是,我想要实现的是计算BlogComment
BlogComment.BlogPostId = BlogPost.BlogPostId
中的行数。
有人有意见吗?
SELECT * FROM BlogPost
INNER JOIN BlogUser
ON BlogPost.BlogUserId = BlogUser.BlogUserId
INNER JOIN Category
ON BlogPost.CategoryId = Category.CategoryId
INNER JOIN BlogComment
ON BlogPost.BlogPostId = BlogComment.BlogPostId
Order By BlogPost.BlogPostId Desc
答案 0 :(得分:1)
每个博客帖子你想要多少评论? 那应该是
SELECT blogpostid,
COUNT(*) as TotalComments
FROM blogpost p
JOIN blogcomment c
ON p.blogpostid = c.blogpostid
GROUP BY blogpostid;
答案 1 :(得分:1)
如果您想要所有数据加上计数(而不仅仅是计数),您可以在from子句中创建内联查询来执行此操作。
SELECT *,
COALESCE(c.count_post_id,0) as count_post_id
FROM blogpost
INNER JOIN bloguser
ON blogpost.bloguserid = bloguser.bloguserid
INNER JOIN category
ON blogpost.categoryid = category.categoryid
LEFT JOIN (SELECT blogpostid,
COUNT(blogpostid) count_post_id
FROM blogcomment
GROUP BY blogpostid) c
ON c.blogpostid = blogpost.blogpostid
ORDER BY blogpost.blogpostid DESC
某些RDMS提供了其他选项,例如使用CTE或Cross Apply
答案 2 :(得分:0)
SELECT COUNT(*)
FROM blogpost a
WHERE EXISTS (SELECT *
FROM blogcomment
WHERE blogcomment.blogpostid = a.blogpostid)
答案 3 :(得分:0)
尝试:
SELECT BlogPost.*, BlogUser.*, Category.*, BlogComment.*, COUNT(BlogComment.BlogCommentId) FROM BlogPost
INNER JOIN BlogUser
ON BlogPost.BlogUserId = BlogUser.BlogUserId
INNER JOIN Category
ON BlogPost.CategoryId = Category.CategoryId
INNER JOIN BlogComment
ON BlogPost.BlogPostId = BlogComment.BlogPostId
GROUP BY BlogPost.BlogPostId Order By BlogPost.BlogPostId Desc