开发者

Selecting a map table of a father-son table

I have a categories table with a father-son relationship which looks something like this:

Table name:

tblCategories

Columns:

catID

catFatherID - This column has a relationship to catID

What I need is to select for each category it's entire family childs (including itself) in the following way:

Original table rows:

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

What I want to get:

| 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 |

Ask if I didn't explain something enough.


A CTE would be a good match to solve this. The trick is to retain a root ID while executing the CTE.

SQL Statement

;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

Test script

;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


You should use recursive SQL with 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

See article at MSDN


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜