【发布时间】: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