2

I realize this is probably painfully simple. Just getting late and need an explanation.

I have the table:

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)

And I need to find the enum of the tuple NOT Python Result should be E403 since its the only one not with Python.

Tried

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

But, obviously, it just returned all the enums...

4 Answers 4

2

One option is the not in operator:

SELECT DISTINCT enum
FROM   employee_expert
WHERE  enum NOT IN (SELECT enum 
                    FROM   employee_expert
                    WHERE  package = 'Python')
Sign up to request clarification or add additional context in comments.

2 Comments

YES. Thank you very much. Had tried the NOT IN but not with a subquery.
(On a properly indexed table, this is the slowest of the 3 solutions provided - just saying)
2

A NOT IN will exclude a subset of data with a specific exclusion criteria:

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

Distinct will exclude duplicates. Sql Fiddle here

1 Comment

Thanks for the help. Can only accept 1. Couldn't tell if you or Mureinik was first to answer.
2

I think that a NOT EXISTS can be faster than NOT IN

SQL Fiddle

MySQL 5.5.32 Schema Setup:

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')
;

Query 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 |

Comments

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.