22,209
社区成员
发帖
与我相关
我的任务
分享
create table tb(id int,parentid int)
insert into tb values(1 ,0)
insert into tb values(2 ,0)
insert into tb values(3 ,0)
insert into tb values(4 ,1)
insert into tb values(5 ,2)
go
select t.* from tb t
where exists(select 1 from tb m where t.parentid = m.id)
or
not exists(select 1 from tb n where t.id = n.parentid)
drop table tb
/*
id parentid
----------- -----------
3 0
4 1
5 2
(所影响的行数为 3 行)
*/
create table tb(id int,parentid int)
insert into tb values(1 ,0)
insert into tb values(2 ,0)
insert into tb values(3 ,0)
insert into tb values(4 ,1)
insert into tb values(5 ,2)
go
select * from tb t
where exists(select 1 from tb m where t.parentid = m.id)
or
not exists(select 1 from tb n where t.id = n.parentid)
drop table tb
/*
id parentid
----------- -----------
3 0
4 1
5 2
(所影响的行数为 3 行)
*/