如何从SQL UNION结果集中移除指定元素(如13)
问题描述
我有如下links表:
| issueid | parentid | type |
|---|---|---|
| 12 | 13 | a |
| 13 | 16 | b |
| 14 | 21 | c |
| 15 | 23 | d |
issueid和parentid均为同一实体的ID。我希望获取不与指定ID(如13)关联的实体ID列表,输入13时期望结果集为(14, 21, 15, 23)——因为13出现在前两行中,属于需排除的关联ID。
我尝试了以下SQL:
SELECT issueid from links where parentid not in (13); -- 返回 13, 14, 15 UNION SELECT parentid from links where issueid not in (13); -- 返回 13, 21, 23 -- UNION 最终结果为 13, 14, 15, 21, 23
现在需要从上述结果集中移除13,请问该如何实现?
解决方法
有几种简单可行的实现方式:
方法一:对UNION结果统一过滤
将UNION的结果作为子查询,在外层直接排除目标ID:
SELECT id FROM ( SELECT issueid AS id from links where parentid NOT IN (13) UNION SELECT parentid AS id from links where issueid NOT IN (13) ) AS combined WHERE id != 13;
方法二:在每个查询分支提前过滤
既然目标是完全排除13,也可以在两个SELECT分支里直接添加过滤条件,避免13进入结果集:
SELECT issueid from links where parentid NOT IN (13) AND issueid != 13 UNION SELECT parentid from links where issueid NOT IN (13) AND parentid != 13;
方法三:使用EXCEPT语法(部分数据库支持)
如果你的数据库支持EXCEPT(如PostgreSQL、SQL Server),可以先获取UNION的完整结果,再减去目标ID:
( SELECT issueid from links where parentid NOT IN (13) UNION SELECT parentid from links where issueid NOT IN (13) ) EXCEPT SELECT 13 AS id;
内容的提问来源于stack exchange,提问作者S.Dan
相关产品推荐
相关产品推荐

