Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 选择父子表的映射表_Sql_Database_Sql Server 2008_Recursive Query - Fatal编程技术网

Sql 选择父子表的映射表

Sql 选择父子表的映射表,sql,database,sql-server-2008,recursive-query,Sql,Database,Sql Server 2008,Recursive Query,我有一个带有父子关系的类别表,看起来像这样: 表名: TBL类别 列: catID catFatherID-此列与catID有关系 我需要的是用以下方式为每个类别选择它的整个家庭孩子(包括它自己): 原始表行: | catID | catFatherID | = = = = = = = = = = = = | 1 | null | | 2 | 1 | | 3 | 1 | | 4 | 2 |


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

表名: TBL类别

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

问我是否解释得不够。

您应该在CTE中使用递归SQL

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
请参见

A将是解决此问题的最佳匹配。诀窍是在执行CTE时保留
ID

SQL语句 测试脚本
您应该保留parentId并在最终结果中选择它。在其当前形式中,这不会返回OP要求的内容。
;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
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