Joost van der Drift
Joost van der Drift

Reputation: 57

In a mysql UNION can I exclude rows from the left part in the right part

I have a table where I store records for either a person or a group.

|id|entity_id|person_id|group_id|
|1 |000000001|999999999|NULL    |
|2 |000000001|NULL     |88888888|
|3 |000000002|999999999|NULL    |
|4 |000000003|NULL     |88888888|

How can I get all the records for person_id 999999999 and group_id 88888888, but the latter only when I do not have a record with entity_id 000000001 for person_id 999999999

So my result should be

|id|entity_id|person_id|group_id|
|1 |000000001|999999999|NULL    |
|3 |000000002|999999999|NULL    |
|4 |000000003|NULL     |88888888|

I am hoping this is possible in one query, but UNION, EXCEPT do not seem to do the trick.

I was trying something like

SELECT *
from myTable m1
WHERE NOT IS NULL person_id
UNION ALL
SELECT *
from myTable m2
WHERE NOT IS NULL group_id
EXCEPT (SELECT entity_id FROM m1)

but apparently mysql doesn't support EXCEPT

Upvotes: 0

Views: 152

Answers (1)

forpas
forpas

Reputation: 164089

Use NOT EXISTS:

SELECT t1.*
FROM tablename t1
WHERE t1.person_id = '999999999'
   OR (
     t1.group_id = '88888888' 
     AND NOT EXISTS (SELECT 1 FROM tablename t2 WHERE t2.entity_id = t1.entity_id AND t2.person_id = '999999999')
   )

See the demo.

Upvotes: 1

Related Questions