表结构:
id parent_id name数据:
0 A
1 0 a
2 0 b
3 1 aa
4 1 saqwqw
5 2 ewqe
6 2 w112。。
我想写个sql,根据已知id上溯得到这个id的第二级数据的name,而不是根A(也就是在我列出的数据中始终得到的是a或者b这两个name,而不是A.打个比方)
id parent_id name数据:
0 A
1 0 a
2 0 b
3 1 aa
4 1 saqwqw
5 2 ewqe
6 2 w112。。
我想写个sql,根据已知id上溯得到这个id的第二级数据的name,而不是根A(也就是在我列出的数据中始终得到的是a或者b这两个name,而不是A.打个比方)
解决方案 »
- 请教一个查询的SQL写法
- SQL2005个人通讯录数据表
- 挑战一sql,一直没有头绪,挺复杂的行列转换,请大家多多指教,等候中.
- SQL表导出到EXCEL,字段类型变为科学技术法的问题!
- SQL语句:感觉很简单的问题,可是我不会~请帮忙
- 各位大哥,如何才能正确地操作视图?谈谈你的们经验好吗?
- 如何将mysql的数据放到sql2005里
- 如何写一个sql语句能根据出生日期按年龄段统计人数?
- 怎么取得sp_addlinkedsrvlogin的返回值,一定要用@@ERROR吗?
- 菜鸟提问,SQL安装程序配置服务器失败。总也装不上SQL。我用的是winxp专业版。不会是系统问题吧。急急急!
- T-SQL 查询 【自动增长1】
- 去掉重复列
set @id=2
;with f as
(
select * from tb where id=@id
union all
select a.* from tb a join f on a.parent_id =f.id
)
select name from f
insert into tb select 0,null,'A'
insert into tb select 1,0,'a'
insert into tb select 2,0,'b'
insert into tb select 3,1,'aa'
insert into tb select 4,1,'saqwqw'
insert into tb select 5,2,'ewqe'
insert into tb select 6,2,'w112'
go
declare @id int
set @id=5
;with cte as(
select * from tb where id=@id
union all
select a.* from tb a inner join cte b on a.id=b.parent_id where a.id<>0
)select * from cte a where not exists(select 1 from cte where id<a.id)
go
drop table tb
/*
id parent_id name
----------- ----------- ----------
2 0 b(1 行受影响)*/
insert into tb select 0,null,'A'
insert into tb select 1,0,'a'
insert into tb select 2,0,'b'
insert into tb select 3,1,'aa'
insert into tb select 4,1,'saqwqw'
insert into tb select 5,2,'ewqe'
insert into tb select 6,2,'w112'
go
declare @id int
set @id=5
;with cte as(
select * from tb where id=@id
union all
select a.* from tb a inner join cte b on a.id=b.parent_id where a.id<>0
)select * from cte a where not exists(select 1 from cte where id<a.id)
go
drop table tb
/*
id parent_id name
----------- ----------- ----------
2 0 b(1 行受影响)*/
这个应该可以,但我的执行提示:在关键字 'with' 附近有语法错误。