MySQL查询列出不属于某种类型的项目

时间:2015-10-10 19:09:20

标签: mysql exists not-exists

我正在尝试获取数据库中account_level IN ('basic', 'full')的公司列表。我们的客户是account_level ='enterprise'。在许多情况下,企业客户端也会在数据库中有行,从那时起他们是基本的或完整的,所以我想排除任何也有企业行的基本/完整公司(即我想排除我们当前的客户)。通过这种方式,我可以获得严格基本或完整的公司列表,但实际上还不是我们的客户。

以下是公司表的一个示例:

1    company a    basic
2    company a    full
3    company b    basic
4    company b    enterprise
5    company c    basic

我希望查询返回公司a和c。

我正在尝试使用:

    SELECT * 
    FROM company c1  
    INNER JOIN company c2 ON c1.id=c2.id
    WHERE c1.company NOT IN  (SELECT c2.company FROM company c2       
    WHERE account_level = 'enterprise')
    AND c1.account_level IN ('full', 'basic')
    ORDER BY c1.company;

但没有结果。有人能看出我做错了吗?对不起,我在mysql中还不是很有经验。谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

您可以使用EXISTSNOT EXISTS

的组合获得所需的结果
SELECT DISTINCT c1.company 
FROM company c1
WHERE EXISTS (SELECT 1 
              FROM company AS c2 
              WHERE c1.company = c2.company AND c2.account_level IN ('full', 'basic'))

      AND

      NOT EXISTS (SELECT 1 
                  FROM company AS c3
                  WHERE c1.company = c3.company AND c3.account_level IN ('enterprise')

或者,甚至更简单:

SELECT DISTINCT c1.company 
FROM company c1
WHERE c1.account_level IN ('full', 'basic'))

      AND

      NOT EXISTS (SELECT 1 
                  FROM company AS c2
                  WHERE c1.company = c2.company AND c2.account_level IN ('enterprise')