SQL查询将检索包含来自另一个集的所有条目的集合

时间:2016-01-27 10:56:37

标签: sql db2

我的数据库中有以下关系:

组织:有关政治和经济组织的信息。
名称:组织的全名
缩写:缩写

isMember:政治和经济组织的成员。
组织:组织的缩写
国家:成员国的代码

geo_desert:有关沙漠的地理信息
沙漠:沙漠的名称
国家:所在的国家代码
省:省国家

我的任务是检索在其成员中拥有沙漠的全套国家/地区的组织。这个组织也可以有没有沙漠的国家。所以我有一组有沙漠的国家,结果中的每个组织都应该把所有组织都作为成员和任意数量的其他(没有沙漠)国家。

到目前为止,我尝试编写以下代码,但它无法正常工作。

WITH CountriesWithDeserts AS (
    SELECT DISTINCT country
    FROM dbmaster.geo_desert        
), OrganizationsWithAllDesertMembers AS (
    SELECT organization 
    FROM dbmaster.isMember AS ism 
    WHERE (
        SELECT count(*)
        FROM (
            SELECT *
            FROM  CountriesWithDeserts          
            EXCEPT
            SELECT country
            FROM dbmaster.isMember
            WHERE organization = ism.organization
        )
    ) IS NULL
), OrganizationCode AS (
    SELECT name, abbreviation
    FROM dbmaster.Organization  
)
SELECT oc.name AS Organization
FROM OrganizationCode AS oc, OrganizationsWithAllDesertMembers AS owadm
WHERE oc.abbreviation=owadm.organization;

UPD: DBMS说:" ism.organization未定义"
我使用的是DB2 / LINUXX8664 9.7.0

输出应如下所示:

NAME
------------------------------------------ --------------------------------------
    非洲,加勒比和太平洋国家
    非洲开发银行     文化技术合作机构
    安第斯集团

3 个答案:

答案 0 :(得分:1)

我发现处理此问题的最简单方法是使用group byhaving。你只想专注于沙漠,所以其他国家都不重要。

select m.organization
from isMember m join
     geo_desert d
     on m.country = d.country
group by m.organization
having count(distinct m.country) = (select count(distinct d.country) from geo_desert);

having条款只计算匹配(即沙漠)国家的数量,并检查所有国家/地区。

答案 1 :(得分:1)

这样说:您正在寻找不存在他们不包括的沙漠国家的组织。

select *
from organization o
where not exists
(
  select country from geo_desert
  except
  select country from ismember
  where organization = o.abbreviation
);

答案 2 :(得分:0)

以下是两个等效的解决方案:


第一:

WITH CountriesWithDeserts AS (
    SELECT DISTINCT country
    FROM dbmaster.geo_desert        
), OrganizationsWithAllDesertMembers AS (
    SELECT ism.organization 
    FROM dbmaster.isMember AS ism
    JOIN CountriesWithDeserts AS cwd
    ON ism.country = cwd.country
    GROUP BY ism.organization
    HAVING count(ism.country) = (SELECT count(*) FROM CountriesWithDeserts)
), OrganizationCode AS (
    SELECT name, abbreviation
    FROM dbmaster.Organization  
)
SELECT oc.name AS Organization
FROM OrganizationCode AS oc, OrganizationsWithAllDesertMembers AS owadm
WHERE oc.abbreviation=owadm.organization;

第二

WITH CountriesWithDeserts AS (
    SELECT DISTINCT country
    FROM dbmaster.geo_desert        
)
SELECT org.name AS Organization
FROM dbmaster.Organization AS org
WHERE NOT EXISTS (
    SELECT *
    FROM  CountriesWithDeserts          
    EXCEPT
    SELECT country
    FROM dbmaster.isMember
    WHERE organization = org.abbreviation
);