我有一个与此类似的数据库:
我查找了一个查询,通过跟踪链接值从表中获取所有值。我不太确定如何用我的英语表达这一点,这就是为什么我通过谷歌找到适当的解决方案有点困难。
实施例: 我有值: Cd 结果应该是这样的: Ab,Bc,Cd,De,Ef (结果不必排序)
感谢您的帮助!
答案 0 :(得分:3)
如果我理解正确,你可以双向关注链接,所以你可以使用递归公用表表达式这样做:
CREATE TABLE #t (C1 varchar(2), C2 varchar(2));
INSERT INTO #t values('Ab','Bc');
INSERT INTO #t values('Bc','Cd');
INSERT INTO #t values('Cd','De');
INSERT INTO #t values('De','Ef');
INSERT INTO #t values('Gh','Hi');
INSERT INTO #t values('Hi','Ij');
DECLARE @start varchar(2) = 'Cd';
WITH cte(vC1, vC2) AS
(
SELECT C1, C2 FROM #t WHERE C1 = @start
UNION ALL
SELECT C1, C2 FROM #t INNER JOIN cte ON vC2 = C1
),
cte2(vC1, vC2) AS
(
SELECT C1, C2 FROM #t WHERE C2 = @start
UNION ALL
SELECT C1, C2 FROM #t INNER JOIN cte2 ON vC1 = C2
)
SELECT vC1 FROM cte
UNION -- unions here add an implicit DISTINCT
SELECT vC2 FROM cte
UNION
SELECT vC1 FROM cte2
UNION
SELECT vC2 FROM cte2