简体   繁体   English

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

[英]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如何获取 person_id 999999999 和 group_id 88888888 的所有记录,但后者仅在我没有 person_id 999999999 的 entity_id 000000001 的记录时

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.我希望这在一个查询中是可能的,但是 UNION, EXCEPT 似乎并不能解决问题。

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但显然 mysql 不支持 EXCEPT

Use NOT EXISTS :使用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 .请参阅演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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