将总数与总数相匹配的好方法是什么?

时间:2014-03-23 14:04:58

标签: postgresql

我有以下问题。似乎是一个简单的查询,但在花了这么多时间之后我无法弄明白。

Table
-----
project
mission
craft

项目可以有很多任务,对于每个任务,它可以使用多个航空工艺品。我想确定所有任务涉及的工艺品。

例如,如果有10个任务,任务1可以使用第1和第2工具。如果有任何工艺用于所有10个任务(任务1 -10),则应该输出。

我写道,

select craft,count(mission) from table group by craft

在此之后,我不知道如何将此值与总任务相匹配。任何帮助都将受到高度赞赏。

2 个答案:

答案 0 :(得分:0)

如果您需要单个项目,则需要根据任务总数来确定飞行任务的过滤器数量:

select c.id from (
   select c.id, count(mission_id) cnt
   from craft c inner join mission m on (m.id = c.mission_id)
   where m.project_id = <project_id> 
   group by c.id
) as c 
where c.cnt = (select count(*) from mission where project_id = <project_id>)

如果所有项目都需要这个:

select c.project_id, c.id from (
   select m.project_id, c.id, count(mission_id) cnt
   from craft c inner join mission m on (m.id = c.mission_id) 
   group by m.project_id, c.id
) as c inner join (
   select project_id, count(*) cnt
   from mission
   group by project_id
) as m on (m.project_id = c.project_id)
where c.cnt = m.cnt

答案 1 :(得分:0)

with mission as (
    select distinct mission
    from craft
), craft_missions as (
    select craft, count(*) as total_missions
    from
        craft c
        inner join
        mission m on m.mission = c.mission
    group by craft
)
select craft
from craft_missions
where total_missions = (select count(*) from mission)