+ -
当前位置:首页 → 问答吧 → 给出一批id,如何查出不在表中的id

给出一批id,如何查出不在表中的id

时间:2011-12-21

来源:互联网

比如我有4个id 1,2,3,4
id为2,3,4的数据在数据表里存在
不存在id为1的数据

怎么写sql返回的id是1

我写的sql是:

SELECT id from rent r1 where id in( 1,2,3,4) and EXISTS (SELECT id from rent r2 where r1.id = r2.id is null)

但是查不出来啊.

作者: dmmc1   发布时间: 2011-12-21

那样查出来的是null..

作者: dmmc1   发布时间: 2011-12-21

SQL code

create table t1
(
    id int
)
insert into t1 (id) values (2),(3),(4)
select * from t1

create table #t
(
    id int
)

declare @str varchar(4000)='1,2,3,4'
set @str=REPLACE(@str,',',' union all select ')
set @str='insert into #t select '+@str
exec (@str)
select * from #t where id not in (select id from t1)
drop table #t

---------------
id
1

作者: gogodiy   发布时间: 2011-12-21