我有以下两个表:
create table person
(
identifier integer not null,
name text not null,
age integer not null,
primary key(identifier)
);
create table agenda
(
identifier integer not null,
name text not null,
primary key(identifier)
);
他们与下表联系在一起:
create table person_agenda
(
person_identifier integer not null,
agenda_identifier integer not null,
primary key(person_identifier, agenda_identifier),
foreign key(person_identifier) references person(identifier),
foreign key(agenda_identifier) references agenda(identifier)
);
我正在尝试引用SELECT
子句中WHERE
子句中定义的数组。
以下作品:
select identifier, name, array(select identifier from agenda a, person_agenda pa where person_identifier = p.identifier and identifier = agenda_identifier and name = '...') as r
from person p;
这不是:
select identifier, name, array(select identifier from agenda a, person_agenda pa where person_identifier = p.identifier and identifier = agenda_identifier and name = '...') as r
from person p
where array_length(r, 1) >= 1;
它说r
不是已知的专栏。如何在WHERE
子句中引用此数组?
我的第二个查询的目的是:
array_length()
> = 1)agenda.name
上)(通过在SELECT
子句中投影数组) 第一个项目符号可以通过简单的连接完成。但是,对于与第二个子弹结合使用的第一个项目符号,我需要对议程标识符进行某种聚合。我认为数组对此很有用。
修改
根据用户Saba的说法,这是不可能的。感谢您的反馈。
以下查询是否是一个不错的选择?
select person.identifier, person.name, array_agg(agenda.identifier)
from person, person_agenda, agenda
where person.identifier = person_identifier and
agenda.identifier = agenda_identifier and
agenda.name = '...'
group by person.identifier;
答案 0 :(得分:0)
Alias不能在WHERE子句中使用,如果要在WHERE子句中使用别名,则需要将其包装在子查询或CTE中。因为查询将按以下顺序执行:
FROM
ON
JOIN
**WHERE**
GROUP BY
WITH CUBE or WITH ROLLUP
HAVING
**SELECT**
DISTINCT
ORDER BY
TOP
尝试这样的事情:
SELECT
FROM (
select identifier, name, array(select identifier from agenda a, person_agenda pa where person_identifier = p.identifier and identifier = agenda_identifier and name = '...') as r
from person p
) AS per
where array_length(r) >= 1;
您的案例似乎很简单,下面的内容适合您:
select person.identifier, person.name, array_agg(agenda.identifier)
from person, person_agenda, agenda
where person.identifier = person_identifier and
agenda.identifier = agenda_identifier and
agenda.name = '...'
group by person.identifier, person.name;