问个sql语句问题

AlifeYuan 2013-05-27 10:02:47
ID PARENTID TYPE
1 NULL 0
2 NULL 0
100 1
200 2 0
300 100
400 200

TYPE 字段有可能为空
PARENTID也就是ID,上一级ID

我现在想要的数据就是,parentid,同时type=0的数据

比如ID=400,它的parentid=200,此时200的type=0,这个200就是我要的
有一种情况,比如300,它的parentid=100,但是type is null,那么需要继续往上找,100的parentid=1,此时1的type=0,那么这个1也是我想要的。

请教下,这种语句怎么写呢?

非常感谢!
...全文
211 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
jascjasc 2013-05-29
  • 打赏
  • 举报
回复
with 
t1 as (select ID, PARENTID,TYPE from 
(select ID, PARENTID,TYPE,row_number()over(order by level)rn from pm_test where type=0  start  with ID in (400)
connect by prior PARENTID=ID)
where rn=1
),
t2 as (select ID, PARENTID,TYPE from 
(select ID, PARENTID,TYPE,row_number()over(order by level)rn from pm_test where type=0  start  with ID in (300)
connect by prior PARENTID=ID)
where rn=1 
)
select * from t1
union all
select * from t2;
kilior 2013-05-29
  • 打赏
  • 举报
回复
老实循环查找吧。。。。。。 这实质上就是找一个树根节点的问题,,,,
nongen 2013-05-29
  • 打赏
  • 举报
回复
目前看上去,楼主的数据只有三级。如果级数再多,, 怎么的要用递归吧。
iceCache 2013-05-28
  • 打赏
  • 举报
回复
select * from 表名 where parentid is not null and type=0
vanjayhsu 2013-05-28
  • 打赏
  • 举报
回复

create table pm_test(ID number, PARENTID number ,TYPE number)
insert into pm_test values(1,     NULL,  0);
insert into pm_test values(2,     NULL,  0);
insert into pm_test values(100,     1,  null);
insert into pm_test values(200,     2,  0);
insert into pm_test values(300,     100,  null);
insert into pm_test values(400,     200,  null);
commit;

select * from(
select t.*,level,row_number() over(order by level) rn from pm_test t where type=0 connect by prior parentid=id start with id=400)
where rn=1

-----------------
rownum  ID	PARENTID	TYPE	LEVEL	RN
1	200	2	0	2	1

似梦飞花 2013-05-28
  • 打赏
  • 举报
回复
start with 。。。connect by 你查下看看是不是你要的
qqq12003 2013-05-28
  • 打赏
  • 举报
回复
SELECT t1.id FROM[表名] t1 CASE WHEN t1.type is null THEN (SELECT type FROM [表名] t2 where t1.parentid=t2.id ) ELSE t1.type=0 END 乱写的,不知道对不对。
qqq12003 2013-05-28
  • 打赏
  • 举报
回复
SELECT id,parentid,type FROM[表名] WHERE id=400 AND parentid=200 AND type=0
AlifeYuan 2013-05-27
  • 打赏
  • 举报
回复
不是的,有可能上一级的type为空的,再上一级的type才是=0
winnie486 2013-05-27
  • 打赏
  • 举报
回复
没看懂。。。直接找TYPE=0不就可以了吗

17,378

社区成员

发帖
与我相关
我的任务
社区描述
Oracle 基础和管理
社区管理员
  • 基础和管理社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧