假设我有以下虚构的数据结构:
```html
我想查询每个国家的人员和事件行数。我决定使用子查询。
我知道您可以使用SELECT语句在字段列表中实现此操作,但使用子查询的优点是我更灵活地修改SQL以使其更加概括并使用其他字段。比如说,如果我将查询改为按大陆显示,只需将字段“c.country_name”替换为“c.continent”即可轻松完成。
我的问题涉及筛选。如果我们添加一个WHERE子句:
子查询似乎仍然对所有国家执行计数。假设人员和事件表很大,并且我已经在所有表上为country_id创建了索引。速度非常慢。数据库不应该只为过滤的国家执行子查询吗?我必须重新创建每个子查询的国家过滤器吗(这非常繁琐,代码不容易修改)?顺便说一下,我同时使用PostgreSQL 8.3和9.0,但我想其他数据库也会发生同样的情况。
```html
让我们假设我有以下虚构的数据结构:
```create table "country"
(
country_id integer,
country_name varchar(50),
continent varchar(50),
constraint country_pkey primary key (country_id)
);
create table "person"
(
person_id integer,
person_name varchar(100),
country_id integer,
constraint person_pkey primary key (person_id)
);
create table "event"
(
event_id integer,
event_desc varchar(100),
country_id integer,
constraint event_pkey primary key (event_id)
);
我想查询每个国家的人员和事件行数。我决定使用子查询。
select c.country_name, sum(sub1.person_count) as person_count, sum(sub2.event_count) as event_count
from
"country" c
left join (select country_id, count(*) as person_count from "person" group by country_id) sub1
on (c.country_id=sub1.country_id)
left join (select country_id, count(*) as event_count from "event" group by country_id) sub2
on (c.country_id=sub2.country_id)
group by c.country_name
我知道您可以使用SELECT语句在字段列表中实现此操作,但使用子查询的优点是我更灵活地修改SQL以使其更加概括并使用其他字段。比如说,如果我将查询改为按大陆显示,只需将字段“c.country_name”替换为“c.continent”即可轻松完成。
我的问题涉及筛选。如果我们添加一个WHERE子句:
select c.country_name,
sum(sub1.person_count) as person_count,
sum(sub2.event_count) as event_count
from
"country" c
left join (select country_id, count(*) as person_count from "person" group by country_id) sub1
on (c.country_id=sub1.country_id)
left join (select country_id, count(*) as event_count from "event" group by country_id) sub2
on (c.country_id=sub2.country_id)
where c.country_name='UNITED STATES'
group by c.country_name
子查询似乎仍然对所有国家执行计数。假设人员和事件表很大,并且我已经在所有表上为country_id创建了索引。速度非常慢。数据库不应该只为过滤的国家执行子查询吗?我必须重新创建每个子查询的国家过滤器吗(这非常繁琐,代码不容易修改)?顺便说一下,我同时使用PostgreSQL 8.3和9.0,但我想其他数据库也会发生同样的情况。