您好,欢迎访问一九零五行业门户网

如何判断多个字段组成的关键字在另外一张表中是否存在

如何判断多个字段组成的关键字在另外一张表中是否存在 老帅(20141107) 1.首先判断一个关键字在另外一张表中是否存在很容易! select * from a where a.id in ( select b.id from b ) 2.如果判断的关键字有多个字段构成怎么办呢? 你不能在in中使用多个字段
如何判断多个字段组成的关键字在另外一张表中是否存在
老帅(20141107)
1.首先判断一个关键字在另外一张表中是否存在很容易!
select * from a
where a.id
in
(
select b.id
from b
)
2.如果判断的关键字有多个字段构成怎么办呢?
你不能在in中使用多个字段。如下查询:
select * from a
where (a.id1, a.id2)
in
(
select b.id1, b.id2
from b
)
这不会正常工作,违反了sqlserver标准。
3.要解决这一问题,可以用exists来代替in!
select * from a
where exists
(
select null
from b
where a.id1 = b.id1
and a.id2 = b.id2
)
4.值得注意的是,这仅适用于in,而非not in!
not in与not exists在处理空值的方式上略有不同。
select *
from a
where (a.id1, a.id2) not in
(
select b.id1, b.id2
from b
)
这不会正常工作,违反了sqlserver标准。要模仿not in的查询如下:
我们必须使用以下查询:
select *
from a
where not exists
(
select null
from b
where a.id1 = b.id1
and a.id2 = b.id2
)
and not exists
(
select null
from b
where b.id1 is null
or b.id2 is null
)
第二个谓词确保b在id1和id2中不会有空值,任何这样的值都会让原始查询不会返回结果!
其它类似信息

推荐信息