SQL语句,以获得所有具有所有能力列表的公司

时间:2014-01-24 15:35:29

标签: sql select

我有一张公司表,我有一张能力表和一张表; companies_competencies

我正试图让所有公司与某个数据集中的所有能力相关联。

因此,例如,我需要让所有拥有1,2和3级能力的公司。

我已经开始使用此查询:

SELECT companies.id, companies.name FROM companies, companies_competencies
WHERE companies.id = companies_competencies.companies_id
AND companies_competencies.competency_id IN(1,2,3)
GROUP BY companies.id

这给了我所有拥有一项或多项能力的公司,但我正在努力让那些专门拥有所有这些公司的公司。

2 个答案:

答案 0 :(得分:5)

这将为您提供具有所有必要能力的公司ID列表:

select companies_id
from companies_competencies
where competency_id in (1, 2, 3)
group by companies_id
having count(distinct competency_id) = 3 --the # of unique competency IDs

然后你可以这样做:

select *
from companies
where id in (
    select companies_id
    from companies_competencies
    where competency_id in (1, 2, 3)
    group by companies_id
    having count(distinct competency_id) = 3
)

答案 1 :(得分:2)

公司是否只拥有各项能力之一?意思是,某个公司只有一个能力ID 1的实例,等等?

如果是这样,既然你已经在分组,你可以像这样修改你的陈述:

SELECT companies.id, companies.name FROM companies, companies_competencies
WHERE companies.id = companies_competencies.companies_id
AND companies_competencies.competency_id IN(1,2,3)
HAVING COUNT(*) = 3
GROUP BY companies.id

这将只返回具有3个记录/能力的公司。