You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从SQL UNION结果集中移除指定元素(如13)

问题描述

我有如下links表:

issueidparentidtype
1213a
1316b
1421c
1523d

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 22:52:57