【问题标题】:For Each Record with Same ID List Values Not in Other Column对于没有在其他列中的具有相同 ID 列表值的每条记录
【发布时间】:2025-12-21 19:45:10
【问题描述】:

我有一个与 ID 号相关联的第 1 部分、第 2 部分、第 3 部分、第 4 部分和第 5 部分的项目列表,如下所示:

ID  | Item
--  | ----
1   | Part 1
1   | Part 2
1   | Part 3
1   | Part 4
2   | Part 1
2   | Part 2
2   | Part 4
2   | Part 5
3   | Part 2
3   | Part 4
3   | Part 5

我想要 Part 列中每个 ID 未找到的每个 Part 的结果集,如下所示:

ID  | Item
--  | ----
1   | Part 5
2   | Part 3
3   | Part 1
3   | Part 3

谁能帮助 SQL 查询生成我的解决方案记录集?

问候,

韦恩

【问题讨论】:

    标签: sql filter missing-data


    【解决方案1】:

    如果ids 和items 带有两个cross join 的两个select distinct 子查询,您可以生成所有可能的组合,然后使用left join 反模式来识别缺失的记录:

    select t1.id, t2.item
    from (select distinct id from mytable) t1
    cross join (select distinct item from mytable) t2
    left join mytable t on t.id = t1.id and t.item = t2.item
    where t.id is null
    order by t1.id, t2.item
    

    这也可以用not exists表示:

    select t1.id, t2.item
    from (select distinct id from mytable) t1
    cross join (select distinct item from mytable) t2
    where not exists (
        select 1
        from mytable t
        where t.id = t1.id and t.item = t2.item
    )
    order by t1.id, t2.item
    

    Demo on DB Fiddle

    编号 |物品 -: | :----- 1 |第 5 部分 2 |第 3 部分 3 |第1部分 3 |第 3 部分

    【讨论】:

    • 专线小巴,这太棒了!这正是我所需要的。非常感谢您这么快提供解决方案!!!
    • 您好 GMB,我终于设法检查了您今天早上提供的查询,并且它们起作用了。它们似乎在比较源表中的唯一值,然后找到缺失值。但我试图做的是与“第 1 部分、第 2 部分、第 3 部分、第 4 部分和第 5 部分”的定义列表进行比较,而不管源表中的值是什么。您知道我将如何检查固定的值列表吗?
    • @WayneWalker:这是一个不同的问题......管理逗号分隔值非常复杂,并且在关系数据库中不鼓励这种设置(你可以看到this famous SO post 长篇大论) .归根结底,我的帖子回答了您提出的问题,没有理由不接受它。如果您还有其他问题,那么您应该提出一个新问题。
    • 专线小巴,我很抱歉。我之前只问了几个问题,所以我想我对我的要求还不够清楚。我的意思不是要从逗号分隔的列表中引用该列表,而是从一个仅在列中列出 Set 值的表中引用该列表。但我会照你说的做,问另一个问题,希望这次能清楚地解释我的需求。再次,抱歉搞砸了。
    • @WayneWalker:没问题。