SQL取最底层的所有解决办法
SQL取最底层的所有
类别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
取到最下级的所有(有下级就不要上级 )
------解决方案--------------------
------解决方案--------------------
------解决方案--------------------
select * from tb a where not exists(select 1 from tb b where a.类别ID=b.上级类别ID)也就是说不存在类别ID跟上级类别ID相等的行数据 能看明白吧
------解决方案--------------------
MSSQL2005及以上版本:
类别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相等的行数据 能看明白吧
------解决方案--------------------
MSSQL2005及以上版本:
CREATE TABLE t1
(
id INT,
mingcheng VARCHAR(10),
pid INT
)
INSERT INTO t1
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 t1
;WITH aaa AS
(
SELECT * FROM t1 WHERE pid=0