2017-11-05 9 views
1

두 개의 테이블, 생산자 및 스키가 있습니다. 생산자는 ID를 가지고 있으며 스키의 각 모델은 생산자의 ID를 알고 있으며 각 모델에도 스키 중 고유하지 않은 유형이 있습니다. 모델에 관계없이 모든 생산자가 생산하는 모든 유형을 선택해야합니다. 나는 쿼리를 썼다 :PostgreSQL : 다른 테이블의 모든 항목에 해당하는 항목이있는 모든 유형 선택

select type 
from skis s 
where not exists (
    select name from producers p 
    except 
    (
     select name 
     from producers p 
     where (p.name=s.producer) 
    ) 
); 

내가 1 명의 스키와 1 명의 제작자를 가지고있을 때만 작동한다. 그렇게하는 좋은 방법은 무엇입니까?

명확한 설명을 위해 편집 : 생산자 테이블에서 'name'열은 ID이고 스키 테이블에서는 생산자 ID 열이 '생산자'입니다.

답변

2

유형에 따라 생산자의 수를 계산하고 생산자의 총 수와 비교 :

select type 
from skis 
group by type 
having count(distinct producer) = (select count(*) from producers); 
1

이 당신을 위해 작동인가?

select s.type 
from 
(
select type, 
     count(distinct producer) amount_producers_for_type 
from skis 
group by type 
) s 
inner join (
      select count(distinct name) number_of_producers 
      from producers 
      ) t 
on t.number_of_producers = s.amount_producers_for_type