有什么方法可以 运行 在 MSSQL 上仅使用部分列的例外查询吗?

Is there any way to run an except query on MSSQL that uses only part of the columns?

我需要做的是:

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

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

然后我得到第二个表:

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

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

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)) 

但是如果我在 table 上都有 "john - null",它将把它们视为未知(既不相等也不不相等)。我知道这样做的原因,但我确实需要它们是平等的。

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

试试这个:

 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 中并联合 table 如果有:

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 值的处理包含到您的查询逻辑中。应该是这样的:

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)
                    )
             );

应该很有魅力。 =)