SQL从具有特定条件的重复项中查找单个值

时间:2014-12-04 18:04:15

标签: mysql sql

我意识到这可能非常简单。只是迟到,需要解释。

我有桌子:

mysql> SELECT * FROM employee_expert;
+------+---------+
| enum | package |
+------+---------+
| E246 | Excel   |
| E246 | MySQL   |
| E246 | Python  |
| E246 | Word    |
| E403 | Java    |
| E403 | MySQL   |
| E892 | Excel   |
| E892 | PHP     |
| E892 | Python  |
+------+---------+
9 rows in set (0.00 sec)

我需要找到元组的enum而不是Python 结果应该是E403,因为它是唯一不使用Python的。

尝试

mysql> SELECT enum FROM employee_expert WHERE package != "Python" GROUP BY enum;
+------+
| enum |
+------+
| E246 |
| E403 |
| E892 |
+------+
3 rows in set (0.00 sec)         

但是,显然,它只返回了所有enum s ...

4 个答案:

答案 0 :(得分:2)

NOT IN将排除具有特定排除标准的数据子集:

SELECT DISTINCT(enum)
FROM employee_expert
WHERE enum NOT IN
(SELECT enum FROM employee_expert WHERE package = 'Python');

Distinct将排除重复项。 Sql Fiddle here

答案 1 :(得分:2)

一个选项是not in运算符:

SELECT DISTINCT enum
FROM   employee_expert
WHERE  enum NOT IN (SELECT enum 
                    FROM   employee_expert
                    WHERE  package = 'Python')

答案 2 :(得分:2)

我认为NOT EXISTS可能比NOT IN

更快

SQL Fiddle

MySQL 5.5.32架构设置

CREATE TABLE employee_expert
    (`enum` varchar(4), `package` varchar(6))
;

INSERT INTO employee_expert
    (`enum`, `package`)
VALUES
    ('E246', 'Excel'),
    ('E246', 'MySQL'),
    ('E246', 'Python'),
    ('E246', 'Word'),
    ('E403', 'Java'),
    ('E403', 'MySQL'),
    ('E892', 'Excel'),
    ('E892', 'PHP'),
    ('E892', 'Python')
;

查询1

SELECT DISTINCT enum 
FROM employee_expert ee1
WHERE NOT EXISTS 
(SELECT 1 
 FROM employee_expert ee2 
 WHERE ee1.enum = ee2.enum AND ee2.package = 'Python')

<强> Results

| ENUM |
|------|
| E403 |

答案 3 :(得分:1)

SELECT DISTINCT x.enum 
           FROM employee_expert x 
           LEFT 
           JOIN employee_expert y 
             ON y.enum = x.enum 
            AND y.package = 'Python' 
          WHERE y.enum IS NULL;