选择父子表的映射表

时间:2011-09-15 09:58:11

标签: sql database sql-server-2008 recursive-query


我有一个父子关系的类别表,看起来像这样:

表名:

tblCategories

栏目:

catID
catFatherID - 此列与catID有关系

我需要的是以下列方式为每个类别选择整个家庭孩子(包括其自身):
原始表格行:

| catID | catFatherID |
= = = = = = = = = = = =
|   1   | null        |
|   2   |  1          |
|   3   |  1          |
|   4   |  2          |
|   5   |  3          |
|   6   |  4          |

我想得到什么:

| Category ID | Family Category ID |
= = = = = = = = = = = = = =  = = = =
| 1 | 1 | (Yes, I want it to include itself in the return family members)
| 1 | 2 |
| 1 | 3 |
| 1 | 4 |
| 1 | 5 |
| 1 | 6 |
| 2 | 2 |
| 2 | 4 |
| 2 | 6 |
| 3 | 3 |
| 3 | 5 |
| 4 | 4 |
| 4 | 6 |
| 5 | 5 |
| 6 | 6 |

问我是否解释不够。

3 个答案:

答案 0 :(得分:1)

您应该使用递归SQL和CTE。

with families(id, parent_id) as (
  select * from tblCategories where id = __initial_id__
  union all
  select t.* from tblCategories as t inner join families as f on t.catFatherID = f.id 
)
 select * from families

请参阅article at MSDN

答案 1 :(得分:1)

CTE可以很好地解决这个问题。诀窍是在执行CTE时保留root ID。

SQL语句

;WITH q AS (
  SELECT  root = catID, catID, catFatherID
  FROM    tblCategories
  UNION ALL
  SELECT  q.root, c.catID, c.catFatherID
  FROM    q 
          INNER JOIN tblCategories c ON c.catFatherID = q.catID 

)
SELECT  root, catID
FROM    q
ORDER BY
        root, catID

测试脚本

;WITH tblCategories (catID, catFatherID) AS (
  SELECT  1, NULL
  UNION ALL SELECT 2, 1
  UNION ALL SELECT 3, 1
  UNION ALL SELECT 4, 2
  UNION ALL SELECT 5, 3
  UNION ALL SELECT 6, 4
)
, q AS (
  SELECT  root = catID, catID, catFatherID
  FROM    tblCategories
  UNION ALL
  SELECT  q.root, c.catID, c.catFatherID
  FROM    q 
          INNER JOIN tblCategories c ON c.catFatherID = q.catID 

)
SELECT  root, catID
FROM    q
ORDER BY
        root, catID

答案 2 :(得分:0)

WITH n(catId, catFatherId) AS 
   (SELECT catId, catFatherId 
    FROM tblCategories 
        UNION ALL
    SELECT n1.catId, n1.catFatherId 
    FROM tblCategories as n1, n
    WHERE n.catId = n1.catFatherId)
SELECT * FROM n