类别ID 类别名称 上级类别ID
1 父类1 0
2 子类11 1
3 子类12 1
4 子子类111 2
5 父类2 0
取到结果
类别ID 类别名称 上级类别ID
3 子类12 1
4 子子类111 2
5 父类2 0
取到最下级的所有(有下级就不要上级 )
------最佳解决方案--------------------
declare @t table( 类别ID int, 类别名称 varchar(20), 上级类别ID int)
insert into @t
select 1,'父类1' ,0 union all
select 2,'子类11' ,1 union all
select 3,'子类12' ,1 union all
select 4,'子子类111',2 union all
select 5,'父类2' ,0
select * from @t t1
where not exists(select 1 from @t t2 where t1.类别ID=t2.上级类别ID)
------其他解决方案--------------------
declare @t table( 类别ID int, 类别名称 nvarchar(20), 上级类别ID int)
insert into @t
select 1,'父类1' ,0
union all select 2,N'子类11' ,1
union all select 3,N'子类12' ,1
union all select 4,N'子子类111',2
union all select 5,N'父类2' ,0
select * from @t a
where not exists(select 1 from @t where a.类别ID=上级类别ID)
/*
类别ID 类别名称 上级类别ID
----------- -------------------- -----------
3 子类12 1
4 子子类111 2
5 父类2 0
(3 row(s) affected)
------其他解决方案--------------------
select * from tb a where not exists(select 1 from tb b where a.类别ID=b.上级类别ID)也就是说不存在类别ID跟上级类别ID相等的行数据 能看明白吧
------其他解决方案--------------------
null
------其他解决方案--------------------
select * from tb a where not exists(select 1 from tb where 上级类别ID=a.类别ID)
------其他解决方案--------------------
新版的code编辑真恶心
------其他解决方案--------------------
MSSQL2005及以上版本:
CREATE TABLE t1