PostgreSQL:选择所有具有与另一个表

时间:2017-11-05 15:34:28

标签: sql postgresql select relational-division

我有两张桌子,制作人和滑雪板。生产者有他们的ID,每个模型的滑雪板都知​​道它的生产者的ID,每个模型也有一个类型,这在滑雪板中不是唯一的。我需要选择所有生产者生产的所有类型(无论模型如何)。我写了一个查询:

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个滑雪板和一个制作人时它才有用。有什么好办法呢?

编辑澄清:在生产者表格中,“name”列是他们的ID,而在滑雪表中,生产者ID列是“生产者”。

2 个答案:

答案 0 :(得分:2)

计算每种类型的生产者数量,并与生产者总数进行比较:

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

答案 1 :(得分: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