PostgreSQL: select all types that have an entry corresponding to all entries in another table

微笑、不失礼 提交于 2019-12-08 07:19:12

问题


I have two tables, producers and skis. Producers have their ID, and each model of skis knows the ID of its producer, each model also has a type, which is not unique among skis. I need to select all types that are produced by all of the producers (regardless of models). I wrote a query:

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

It only works when I have 1 ski and one producer. What is a good way to do that?

EDIT for clarification: in the producer table, the column 'name' is their ID, and in the ski table the producers ID column is 'producer'.


回答1:


Count the number of producers per type and compare with the total number of producers:

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



回答2:


Is it work for you?

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


来源:https://stackoverflow.com/questions/47123352/postgresql-select-all-types-that-have-an-entry-corresponding-to-all-entries-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!