sql语句 查询 类别下所有子类 5
如下(ID)类别ID(Name)类型名称(FID)父类ID1一级102一级203二级124二级225三级146四级157二级11求一条sql语句查询出,ID为2,3,4,...
如下
(ID)类别ID (Name) 类型名称 (FID)父类ID
1 一级1 0
2 一级2 0
3 二级1 2
4 二级2 2
5 三级1 4
6 四级1 5
7 二级1 1
求一条sql语句查询出,ID为2,3,4,5,6这几条数据 展开
(ID)类别ID (Name) 类型名称 (FID)父类ID
1 一级1 0
2 一级2 0
3 二级1 2
4 二级2 2
5 三级1 4
6 四级1 5
7 二级1 1
求一条sql语句查询出,ID为2,3,4,5,6这几条数据 展开
4个回答
展开全部
create table tb
(
ID int,
name varchar(20),
FID int
)
insert into tb values( 1,'一级1',0)
insert into tb values( 2,'一级2',0)
insert into tb values( 3,'二级1',2)
insert into tb values( 4,'二级2',2)
insert into tb values( 5,'三级1',4)
insert into tb values( 6,'四级1',5)
insert into tb values( 7,'二级1',1)
with tmp(id,name,fid) as
(
select id,name,fid from tb where id in (2)
union all
select tb.id,tb.name,tb.fid from tb inner join tmp on tb.fid = tmp.id
)
select distinct * from tmp order by id,fid
2 一级2 0
3 二级1 2
4 二级2 2
5 三级1 4
6 四级1 5
(
ID int,
name varchar(20),
FID int
)
insert into tb values( 1,'一级1',0)
insert into tb values( 2,'一级2',0)
insert into tb values( 3,'二级1',2)
insert into tb values( 4,'二级2',2)
insert into tb values( 5,'三级1',4)
insert into tb values( 6,'四级1',5)
insert into tb values( 7,'二级1',1)
with tmp(id,name,fid) as
(
select id,name,fid from tb where id in (2)
union all
select tb.id,tb.name,tb.fid from tb inner join tmp on tb.fid = tmp.id
)
select distinct * from tmp order by id,fid
2 一级2 0
3 二级1 2
4 二级2 2
5 三级1 4
6 四级1 5
展开全部
--假如表名是 tablea
select *
from tablea b
where ID between 2 and 6
union all
select *
from tablea a
where exists
(
select *
from tablea b
where b.ID between 2 and 6
and a.ID=b.FID
)
--第二办法是使用递归
with
temp
as
(
select *
from tablea
where ID between 2 and 6
union all
select b.*
from temp
inner join tablea b on b.ID=temp.ID
)
select *
from temp
select *
from tablea b
where ID between 2 and 6
union all
select *
from tablea a
where exists
(
select *
from tablea b
where b.ID between 2 and 6
and a.ID=b.FID
)
--第二办法是使用递归
with
temp
as
(
select *
from tablea
where ID between 2 and 6
union all
select b.*
from temp
inner join tablea b on b.ID=temp.ID
)
select *
from temp
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
2014-09-23
展开全部
select * from TABLE where id in (2,3,4,5,6);
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
select * from table where id in (2,3,4,5,6)
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询