使用两个select语句的下面的查询有效:
create or replace view q2 as
select count(p.id) nstudents,
(select count(p.id) nstaff
from people p, staff s where p.id = s.id)
from people p, students s where p.id = s.id;
但是当我包含第三个子查询时:
create or replace view q2 as
select count(p.id) nstudents,
(select count(p.id) nstaff,
(select count(p.id) nboth
from people p, students s, staff t where p. id = s.id and p.id = t.id)
from people p, staff t where p.id = t.id)
from people p, students s where p.id = s.id;
它给了我以下错误:
ERROR: subquery must return only one column
LINE 3: (select count(p.id) nstaff,
我在包含第三个查询时是否犯了一些错误,或者只有2个嵌套选择语句的限制?
答案 0 :(得分:2)
带有附加子查询的版本失败了,因为您将第二个子查询插入第一个子查询时,它应该像这样:
select count(p.id) nstudents,
(select count(p.id) from people p, staff t where p.id = t.id) nstaff ,
(select count(p.id) from people p, students s, staff t where p. id = s.id and p.id = t.id) nboth
from people p, students s where p.id = s.id;
但是,查询也可以使用条件聚合(以及使用显式ANSI标准连接)来编写,如下所示:
select
sum(case when s.id is not null then 1 end) nstudents,
sum(case when t.id is not null then 1 end) nstaff,
sum(case when s.id is not null and t.id is not null then 1 end) nboth
from people p
left join students s on p. id = s.id
left join staff t on p.id = t.id