【问题标题】:In a mysql UNION can I exclude rows from the left part in the right part在 mysql UNION 中,我可以在右侧排除左侧的行吗
【发布时间】:2021-08-27 09:24:30
【问题描述】:

我有一个表,用于存储个人或组的记录。

|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 999999999 的 entity_id 为 000000001 的记录时才能获取后者

所以我的结果应该是

|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

【问题讨论】:

  • 如果是我,我会考虑只存储group_ids,并要求每个人都是一个组的成员(即使是一个1人的组)
  • @strawberry 人始终是组的成员,但该人的条目会覆盖该组的条目

标签: mysql union except


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-29
    • 1970-01-01
    • 1970-01-01
    • 2018-03-31
    • 1970-01-01
    相关资源
    最近更新 更多