首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

SQL取最底层的全部

2012-12-21 
SQL取最底层的所有类别ID类别名称上级类别ID1父类102子类1113子类1214子子类11125父类20取到结果类别ID类

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

取到最下级的所有(有下级就不要上级 )
[最优解释]

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


(
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
UNION ALL
SELECT a1.* FROM t1 AS a1 INNER JOIN aaa AS b1 ON a1.pid=b1.id
)
SELECT * FROM aaa WHERE pid>0

------------------
idmingchengpid
2子类111
3子类121
4子子类1112

热点排行