代码拉取完成,页面将自动刷新
-- 建测试表
CREATE TABLE DEMO (
ID varchar ( 10 ) PRIMARY KEY,
DSC varchar ( 100 ),
PID varchar ( 10 )
);
Insert Into DEMO values ('00001', '中国', '-1');
Insert Into DEMO values ('00011', '陕西', '00001');
Insert Into DEMO values ('00012', '贵州', '00001');
Insert Into DEMO values ('00013', '河南', '00001');
Insert Into DEMO values ('00111', '西安', '00011');
insert Into DEMO values ('00112', '咸阳', '00011');
Insert Into DEMO values ('00113', '延安', '00011');
select * from demo;
-- SELECT * FROM start_demo start with id = '00001' Connect By Prior id = pid;
-- start with 的作用就是从当前id为 00001的通过ID=pid进行连接,并递归查询,把ID=00001的后代都查出来
-- SELECT * FROM start_demo start with id = '00113' Connect By Prior PID = id
-- 上一条记录的PID是本条记录的ID,找祖宗
SELECT
id, dsc, pid
FROM
demo d1
WHERE NOT EXISTS(
select * from demo d2,demo d3 where d2.ID=d3.PID AND d1.ID=d2.ID
);
-- 根据当前ID找到父级的循环
WITH recursive t AS
(
SELECT *
FROM demo
WHERE id = '00111'
UNION ALL
SELECT a.*
FROM demo a, t b
WHERE a.id = b.pid
)
SELECT *
FROM t;
-- 根据当前PID找到所有子级的循环
WITH recursive t AS
(
SELECT *
FROM demo
WHERE pid = '00001'
UNION ALL
SELECT a.*
FROM demo a, t b
WHERE a.pid = b.id
)
SELECT *
FROM t;
-- 根据当前ID找到所有子级的循环
WITH recursive t AS
(
SELECT *
FROM demo
WHERE id = '00011'
UNION ALL
SELECT a.*
FROM demo a, t b
WHERE a.pid = b.id
)
SELECT *
FROM t;
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。