递归SQL语句
条件:B字段值=e,查询出所有围绕e产生关系的A、B字段的值,字段描述如下:字段A(父节点):a、b、c、d、e、a、a、g、m字段B(子节点):b、c、d、e、f、g、...
条件:B字段值=e,查询出所有围绕e产生关系的A、B字段的值,字段描述如下:
字段A(父节点):a、b、c、d、e、a、a、g、m
字段B(子节点):b、c、d、e、f、g、h、m、n
字段B中e的父节点为d,但d同时也存在子节点中,继续遍历查询,最终查询到所有已e为中心的对应关系及最高父节点和最下面子节点。 展开
字段A(父节点):a、b、c、d、e、a、a、g、m
字段B(子节点):b、c、d、e、f、g、h、m、n
字段B中e的父节点为d,但d同时也存在子节点中,继续遍历查询,最终查询到所有已e为中心的对应关系及最高父节点和最下面子节点。 展开
推荐于2016-06-10
展开全部
CREATE TABLE #test (
A char(1),
B char(1)
)
GO
INSERT INTO #test VALUES('a', 'b');
INSERT INTO #test VALUES('b', 'c');
INSERT INTO #test VALUES('c', 'd');
INSERT INTO #test VALUES('d', 'e');
INSERT INTO #test VALUES('e', 'f');
INSERT INTO #test VALUES('a', 'g');
INSERT INTO #test VALUES('a', 'h');
INSERT INTO #test VALUES('g', 'm');
INSERT INTO #test VALUES('m', 'n');
GO
With myCTE AS
(
SELECT
0 AS Level, A, B
FROM
#test
WHERE
B = 'e'
UNION ALL
SELECT
myCTE.Level + 1 AS Level,
t.A, t.B
FROM
#test t JOIN myCTE ON (myCTE.A = t.B)
)
SELECT top 1
A AS [最高父节点]
FROM
myCTE
ORDER BY
Level DESC
GO
最高父节点
-----
a
(1 行受影响)
With myCTE AS
(
SELECT
0 AS Level, A, B
FROM
#test
WHERE
B = 'e'
UNION ALL
SELECT
myCTE.Level + 1 AS Level,
t.A, t.B
FROM
#test t JOIN myCTE ON (myCTE.B = t.A)
)
SELECT top 1
B AS [最下面子节点]
FROM
myCTE
ORDER BY
Level DESC
GO
最下面子节点
------
f
(1 行受影响)
SQL Server 2008 Express 版本下测试通过。
追问
看结果没什么问题,没sql server验证啊,能用oracle库做么?多谢多谢~
追答
CREATE TABLE test (
A char(1),
B char(1)
);
INSERT INTO test VALUES('a', 'b');
INSERT INTO test VALUES('b', 'c');
INSERT INTO test VALUES('c', 'd');
INSERT INTO test VALUES('d', 'e');
INSERT INTO test VALUES('e', 'f');
INSERT INTO test VALUES('a', 'g');
INSERT INTO test VALUES('a', 'h');
INSERT INTO test VALUES('g', 'm');
INSERT INTO test VALUES('m', 'n');
-- 最高父节点
SELECT
A
FROM
(
SELECT
LEVEL, A
FROM
test
START WITH
B = 'e'
CONNECT BY B = PRIOR A
ORDER BY LEVEL DESC
) subQuery
WHERE
ROWNUM = 1;
-- 最下面子节点
SELECT
B
FROM
(
SELECT
LEVEL, B
FROM
test
START WITH
B = 'e'
CONNECT BY PRIOR B = A
ORDER BY LEVEL DESC
) subQuery
WHERE
ROWNUM = 1;
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询