简体   繁体   中英

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM