【问题标题】:Is there any way to run an except query on MSSQL that uses only part of the columns?有没有办法在只使用部分列的 MSSQL 上运行除查询?
【发布时间】:2017-03-10 08:04:15
【问题描述】:

我需要做的是:

我的数据库中有一个这样的表:

idx   |   name   |   age
------ ---------- -------
 1    |   John   |    18
 2    |   Marry  |    19
 3    |   Eric   |    17

然后我得到一个 secondTable:

name  |  age
------ -----
Moses |   29
John  |   18
Eric  |   20

我想运行一个 except 查询,例如:

select   * 
from     firstTable 
where    (name, age) not in (select * from secondTable)

和这样的相交查询:

select   * 
from     firstTable 
where    (name, age) in (select * from secondTable)

所以第一个查询的结果是:

2   | Marry  | 19
---- -------- ----
3   | Eric   | 17

第二个查询的结果是:

1   |  John  | 18

我还找到了以下建议的解决方案:

select  * 
from    firstTable 
where   EXISTS (select 1 
                from   secondTable 
                where  firstTable.name = secondTable.name 
                and    firstTable.age = secondTable.age)) 

但是如果我在两个表上都有“john - null”,它会将它们视为未知(既不相等也不不相等)。我知道原因,但我确实需要他们平等。

我需要这样做的原因是为了将当前索引值保留到查询结果中。

【问题讨论】:

  • 添加 isnull(age,'') 并检查
  • 或者设置 EXISTS 像EXISTS (select 1 from secondTable where firstTable.name = secondTable.name AND (firstTable.age = secondTable.age OR firstTable.age IS NULL AND secondTable.age IS NULL)))? (我刚刚扩展了你的最后一个子句以包含 NULL 案例)
  • 你是什么意思“将它们视为未知数”?您的意思是删除重复项?
  • @MK_ 你的解决方案很有魅力!!!!如果你把它变成一个答案,我会更乐意支持它!
  • 然后将他标记为已回答.. 给@MK_

标签: sql-server sql-except


【解决方案1】:

您只需要将处理NULL 值包含到您的查询逻辑中。应该是这样的:

SELECT * 
FROM firstTable 
WHERE EXISTS (SELECT TOP(1) 1 
              FROM secondTable 
              WHERE firstTable.name = secondTable.name
                AND (
                      firstTable.age = secondTable.age
                      OR
                      (firstTable.age IS NULL AND secondTable.age IS NULL)
                    )
             );

应该像魅力一样工作。 =)

【讨论】:

    【解决方案2】:

    试试这个:

     select distinct a.idx,a.name,a.age,b.name,b.age from first_table as a
     inner join 
     second_table as b
     on a.name = b.name and a.age = b.age
    

    这个只显示first_table和second_table具有相同值的记录

    如果有,则此查询不在 second_table 和 union 两个表中显示:

    select distinct a.idx,b.name,b.age from first_table as a
    inner join 
    second_table as b
    on a.name = b.name and a.age = b.age
    
    union all
    
    select a.idx,a.name,a.age 
    from first_table as a where a.name not in(select name from second_table)
    

    【讨论】:

    • 你的解决方案不是还有 null 不是值的问题吗?
    • 谢谢,请在这里显示您的预期结果,以便我可以更新我的答案?
    • 我已经在我的问题中写下了预期的结果。但我已经得到了@MK_ 的答复。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-16
    • 1970-01-01
    • 2021-07-02
    • 2019-10-30
    • 2019-02-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多