何苦呢 select * from tb1 where tb_id not in (1,2,5) 这已经是最简单的写法了
select * from tb1 a where not exists(select 1 from ( select 1 as id union select 2 union select 3) b where a.tb_id = b.id)
这是ANSI的标准语法,你指的兼容性问题是什么?NOT IN vs NOT EXISTS的区别,除了null问题之外,就是not in容易出现一些非逻辑性错误。USE Northwind; GO SELECT * FROM Shippers WHERE ShipperID NOT IN ( SELECT ShipperID FROM Orders ) orders 中没有shipperid 字段,但语句不会报错,而是会转成NOT IN (Shippers.ShipperiD...)至於用哪一个效率高,要看执行计划是怎么生成的,单单说not in 比not exists差是毫无根据的。
另外,如果是or的话,好象一条都出不来另外,什么情况下最好用exists替换in,因为听说exists效率比in高,而且in是为了兼容低版本的,以后版本的未必用的上
select * from tb1 where not exists (select 1 from tb1 where tb_id=1 or tb_id =2 ortb_id =5)
select * from tb1 where not exists (select 1 from tb1 where tb_id=1 or tb_id =2 or tb_id =5)好像查不出结果啊!关注中。
select * from tb1 where tb_id not in (1,2,5)
这已经是最简单的写法了
from tb1 a
where not exists(select 1 from ( select 1 as id union select 2 union select 3) b where a.tb_id = b.id)
GO
SELECT * FROM Shippers
WHERE ShipperID NOT IN
(
SELECT ShipperID FROM Orders
)
orders 中没有shipperid 字段,但语句不会报错,而是会转成NOT IN (Shippers.ShipperiD...)至於用哪一个效率高,要看执行计划是怎么生成的,单单说not in 比not exists差是毫无根据的。