Чтобы получить ноль для поста без комментариев, 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
Вот почему 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