我有两个表格如下所示:
**tblComments**
Commentid
addeddate
Postid
**tblPosts**
Postid
AddedBy
AddedDate
Title
我想找到每篇帖子的总评论。怎么办?
答案 0 :(得分:3)
您需要加入表格以查找没有评论的帖子以生成零
select
count(c.postid), P.postid --edit
from
tblPosts P
LEFT JOIN
tblComments C On P.postid = C.postid
group by
P.postid
答案 1 :(得分:1)
为没有评论的帖子生成零,T-SQL:
select
P.postid, count(c.postid) -- should not use COUNT(*) for LEFT JOINs
from
tblPosts P
LEFT JOIN
tblComments C On P.postid = C.postid
group by
P.postid
对于Postgresql,获取行的基数:
select
P.postid, count(c.*) -- should not use COUNT(*) for LEFT JOINs
from
tblPosts P
LEFT JOIN
tblComments C On P.postid = C.postid
group by
P.postid
与此相关:http://www.ienablemuch.com/2010/04/debunking-myth-that-countdracula-is.html
这就是不应该在LEFT JOIN上使用COUNT(*)的原因:
create table posts
(
post_id int identity(1,1) not null primary key,
post varchar(max)
);
create table comments
(
post_id int not null references posts(post_id),
comment_id int identity(1,1) not null primary key,
comment varchar(max)
);
insert into posts(post) values('hello');
insert into posts(post) values('oh hai');
insert into comments(post_id,comment) values(SCOPE_IDENTITY(), 1);
-- don't
select p.post_id, COUNT(*) as comment_count from
posts p
left join comments c on c.post_id = p.post_id
group by p.post_id
-- do
select p.post_id, COUNT(c.post_id) as comment_count from
posts p
left join comments c on c.post_id = p.post_id
group by p.post_id
输出:
post_id comment_count
----------- -------------
1 1
2 1
post_id comment_count
----------- -------------
1 0
2 1
查询样式在Postgresql上更具吸引力,想到它,我们真正在计算的是集合的基数,而不是列:
-- looks better on Postgresql, COUNT(c.*)
select p.post_id, COUNT(c.*) as comment_count from
posts p
left join comments c on c.post_id = p.post_id
group by p.post_id
答案 2 :(得分:0)
select count(*), postid from tblPosts group by postid
应该做我想过的伎俩
答案 3 :(得分:0)
编辑:根据您的评论编辑,以获取所有帖子,包括0评论。 试试看。我认为这应该像你期望的那样工作
SELECT p.Postid, p.Title, ISNULL(X.count,0)
FROM tblPosts p
LEFT OUTER JOIN
(SELECT postid, count(commentid) as Total
FROM tblComments
GROUP BY Postid) AS X
ON p.Postid = X.Postid
答案 4 :(得分:0)
select case(when count(commentid)>0 then count(commentid) else 0 end), postid from tblPosts group by postid