2015-01-16 2 views
1

내가 가지고있는 다음과 같은 두 개의 테이블 :에 SELECT 절에서 배열을 참조 WHERE 절

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 절 배열을 투영함으로써) 제 1 탄환 가입을 간단하여 수행 할 수있다. 그러나 두 번째 글 머리 기호와 결합 된 첫 번째 글 머리표의 경우 아젠다 식별자에 일종의 집계가 필요합니다. 배열이 유용 할 거라고 생각 했어.

편집

사용자 사바에 따르면,이 수 없습니다. 귀하의 의견에 감사드립니다.

다음 쿼리가 좋은 대안입니까? 당신이 당신의 WHERE 절에 별칭을 사용하려는 경우

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

별칭이 WHERE 절에 사용하지 못할, 당신은 하위 쿼리 또는 CTE에 포장해야합니다. ,

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; 

귀하의 경우 곧장 앞으로 것 하나 아래 당신을 위해 작동합니다 :

FROM 
ON 
JOIN 
**WHERE** 
GROUP BY 
WITH CUBE or WITH ROLLUP 
HAVING 
**SELECT** 
DISTINCT 
ORDER BY 
TOP 

이 같은 것을보십시오 :

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; 
+0

감사 질의는 다음과 같은 순서로 실행됩니다 때문에 . 'WHERE'는 실제로'SELECT' 전에 실행됩니다. 두 개의 글 머리 기호를 여전히 충족시키는 하위 쿼리에서 두 번째 쿼리를 다시 작성하려면 어떻게해야합니까? –

+0

내 게시물을 편집했습니다. 이것은 좋은 해결책입니까? –

+0

수정 해 주셔서 감사합니다. 하위 쿼리의 Wrappig는 꽤 영리합니다. 이것은 또한 작동합니다! –