有2个表,video
和category
。
create table category (
id integer primary key,
name text
);
create table video (
id integer primary key,
category_id integer references category (id),
quality text
);
insert into category (id, name) values (1, 'Entertainment');
insert into category (id, name) values (2, 'Drawing');
insert into video (id, category_id, quality) values (1, 1, 'sd');
insert into video (id, category_id, quality) values (2, 1, 'hd');
insert into video (id, category_id, quality) values (3, 1, 'hd');
我可以获取所有类别的列表以及所有视频的数量。
select category.id, category.name, count(video)
from category left outer join video
on (category.id = video.category_id)
group by category.id;
结果
id | name | count
----+---------------+-------
2 | Drawing | 0
1 | Entertainment | 3
(2 rows)
要获得具有高清视频数量的所有类别,可以使用这两个查询。
带过滤器的计数
select
category.id,
category.name,
count(video) filter (where video.quality='hd')
from category left outer join video
on (category.id = video.category_id)
group by category.id;
结果
id | name | count
----+---------------+-------
2 | Drawing | 0
1 | Entertainment | 2
(2 rows)
on
select
category.id,
category.name,
count(video)
from category left outer join video
on (category.id = video.category_id and video.quality='hd')
group by category.id;
结果
id | name | count
----+---------------+-------
2 | Drawing | 0
1 | Entertainment | 2
(2 rows)
结果相等。使用第一种和第二种方法的优缺点是什么?首选哪一个?
第二个查询以某种方式更有效,因为on
的join
谓词减少了较早的行数,而第一个查询保留了所有行,然后依赖于聚合函数的过滤器。我建议第二个查询。
例如,如果您要执行多个条件计数,则第一个查询将很有用,例如:
select
category.id,
category.name,
count(video) filter (where video.quality='hd') no_hd_videos,
count(video) filter (where video.quality='sd') no_sd_videos
from category left outer join video
on (category.id = video.category_id)
group by category.id;