多级或树结构中的所有父级联合

时间:2016-10-22 13:44:20

标签: sql sql-server

我有2张桌子

1. parent table and 2. Child Table

父表值

Pid parent_name
1  A 
2  B
3  D
4  H
5  J

子表值

Chid Pid child_name
1     1   B
2     1   C
3     1   D
4     2   F
5     2   G
6     3   H
7     3   I
8     4   J
9     4   K
10    5   L

当我输入输入A然后我将输出为

Pid
B
D
H
J

当我输入输入D然后我将输出为

Pid
H
J

当我给父母姓名时,就像树结构那样结果将是所有孩子,孙子,大孩子...... 所有有孩子的父母

2 个答案:

答案 0 :(得分:0)

您需要使用递归CTE来达到目的。

 DECLARE @Id varchar(10)='your_pid' 
;WITH cte AS 
 (
  SELECT b.pid, b.chid, b.parent_name
  FROM parent a inner join child b on b.pid= a.pid
  WHERE b.pid = @Id
  UNION ALL
  SELECT b.pid
  FROM parent a inner join child b on b.pid= a.pid
  inner join cte on cte.pid= b.chid
  WHERE b.pid = @Id  )
  SELECT parent_name
  FROM cte

答案 1 :(得分:0)

我相信您需要将父子记录存储在单个表中,如下所示:

1   NULL    A
2   1   B
3   1   C
4   1   D
5   2   F
6   2   G
7   4   H
8   4   I
9   7   J
10  7   K
11  9   L

然后您可以按如下方式查询数据:

WITH T (id, pid, name) AS (
    SELECT 1, NULL, 'A'
    UNION ALL
    SELECT 2, 1, 'B'
    UNION ALL
    SELECT 3, 1, 'C'
    UNION ALL
    SELECT 4, 1, 'D'
    UNION ALL
    SELECT 5, 2, 'F'
    UNION ALL
    SELECT 6, 2, 'G'
    UNION ALL
    SELECT 7, 4, 'H'
    UNION ALL
    SELECT 8, 4, 'I'
    UNION ALL
    SELECT 9, 7, 'J'
    UNION ALL
    SELECT 10, 7, 'K'
    UNION ALL
    SELECT 11, 9, 'L'
), U AS (
    SELECT B.* FROM T A JOIN T B ON B.pid = A.id JOIN T C ON C.pid = B.id WHERE A.name = 'A'
    UNION ALL
    SELECT P.* FROM T P JOIN U Q ON Q.id = P.pid JOIN T R ON R.pid = P.id
)
SELECT DISTINCT name FROM U

例如,如果您的表名为“tbl”,那么:

WITH T (id, pid, name) AS (
    SELECT id, pid, name FROM tbl
), U AS (
    SELECT B.* FROM T A JOIN T B ON B.pid = A.id JOIN T C ON C.pid = B.id WHERE A.name = 'A'
    UNION ALL
    SELECT P.* FROM T P JOIN U Q ON Q.id = P.pid JOIN T R ON R.pid = P.id
)
SELECT DISTINCT name FROM U