在 mysql UNION 中,我可以从右侧部分的左侧部分排除行吗

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

我有一个 table 存储个人或组记录的地方。

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

如何获取 person_id 999999999 和 group_id 88888888 的所有记录,但后者仅当我没有 person_id 000000001 的 entity_id 记录时] 999999999

所以我的结果应该是

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

我希望这可以在一个查询中实现,但 UNION、EXCEPT 似乎无法解决问题。

我正在尝试类似

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)

但显然 mysql 不支持 EXCEPT

使用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')
   )

参见demo