【问题标题】:Get records which are not in tables when passed in In clause?在 In 子句中传递时获取不在表中的记录?
【发布时间】:2016-10-01 07:52:48
【问题描述】:

我确定问题的标题需要更改,但不知道该放什么。

我在两个表中传递 In 子句想要获取两个表中都不存在的记录。

表 A 包含 ID 1,2 表 B 包含 ID 3,4

我正在传递我的 In 子句 (1,2,3,4,5,6)

我在找东西

1 TableA
2 TableA
3 TableB
4 TableB
5 Not Found
6 Not Found

我正在使用 union all 从表 A 和表 B 中获取项目,不知道如何获取两个表中未找到的记录?

【问题讨论】:

  • 通过您的样本,您期望的结果是什么? (5,6)? (1,2)? ...?
  • 除非您提供一些详细信息,否则我们也不会。除了没有任何实际细节的伪代码之外,没有人可以做很多事情。你可以看看这篇文章。 spaghettidba.com/2015/04/24/…
  • 我想要 In Clause 中传递的所有记录 .. 以及它们属于哪个表,如果在任何表中都不存在,则没有找到
  • 如果它们在两个表中怎么办?如果没有任何细节,我们只能提供可能与您想要的或可能不会接近的模糊示例。
  • @SeanLange 我会发布更多细节,谢谢

标签: sql sql-server database join union


【解决方案1】:

这是一种方法。它使用exists 来检查表是否包含id

select id,
       (case when inA = 1 and inB = 1 then 'Both'
             when inA = 1 then 'TableA'
             when inB = 1 then 'TableB'
             else 'Not Found'
        end) as status
from (select id,
             (case when exists (select 1 from tableA a where a.id = ids.id then 1 else 0 end) as inA,
             (case when exists (select 1 from tableB b where b.id = ids.id then 1 else 0 end) as inB
      from (values (1), (2), (3), (4), (5), (6)) as ids(id)
     ) i;

当然,如果您不想要 'Both' 行,您可以添加 where inA = 0 or inB = 0

【讨论】:

    【解决方案2】:

    尝试以下查询:

    DECLARE @TableA TABLE (Col1 INT)
    INSERT  @TableA VALUES (1), (2),(5)
    
    DECLARE @TableB TABLE (Col2 INT)
    INSERT  @TableB VALUES (3), (4),(5)
    
    -- Query
    SELECT t.Col3,
        CONCAT(xa.ExistsInA, ',', xb.ExistsInB) AS SourceTables
        --STUFF(CONCAT(',' + xa.ExistsInA, ',' + xb.ExistsInB), 1, 1, '') AS SourceTables
    FROM (VALUES
        (1),
        (2),
        (3),
        (4),
        (5),
        (6)
    ) AS t(Col3)
    OUTER APPLY (
        SELECT  'TableA'
        WHERE   EXISTS(SELECT * FROM @TableA a WHERE a.Col1 = t.Col3)
    ) xa (ExistsInA)
    OUTER APPLY (
        SELECT  'TableB'
        WHERE   EXISTS(SELECT * FROM @TableB b WHERE b.Col2 = t.Col3)
    ) xb (ExistsInB)
    

    【讨论】:

      猜你喜欢
      • 2018-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-07
      • 1970-01-01
      • 2014-07-16
      • 1970-01-01
      相关资源
      最近更新 更多