gpt4 book ai didi

sql - 选择父子表的映射表

转载 作者:搜寻专家 更新时间:2023-10-30 23:20:21 27 4
gpt4 key购买 nike


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

表名:

tbl类别

列:

猫ID
catFatherID - 此列与 catID
有关系

我需要按以下方式为每个类别选择整个家庭的 child (包括它自己):
原始表行:

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

问我是不是解释不够。

最佳答案

A 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

关于sql - 选择父子表的映射表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7429050/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com