gpt4 book ai didi

sql-server - 如何在 SQL 中的单个列中显示递归 parentID

转载 作者:行者123 更新时间:2023-12-03 17:07:00 26 4
gpt4 key购买 nike

这是表的示例结构:

ID    Name     ParentID
-----------------------
1 Ancestor NULL
2 GrandFather 1
3 GrandMother 1
4 Child 3

我正在尝试编写一个会返回的查询
ID     Name        Family
----------------------------
1 Ancestor
2 GrandFather Ancestor
3 GrandMother Ancestor
4 Child Ancestor^GrandMother

棘手的部分是我想以自上而下的顺序显示所有行的族。

如果有人能指出我正确的方向,我将不胜感激:)

编辑::这是真正的查询,但它遵循相同的想法。它在线返回错误:marketparent.family + '^'+ t2.marketGroupName 因为它找不到 marketparent
WITH marketparent ( marketGroupID,parentGroupID, marketGroupName,family)
AS
(
SELECT marketGroupID,
parentGroupID,
marketGroupName,
'' as family
FROM EVE.dbo.invMarketGroups
WHERE parentGroupID IS NULL
UNION ALL

SELECT t2.parentGroupID,
t2.marketGroupID,
t2.marketGroupName,
marketparent.family + '^'+ t2.marketGroupName
FROM EVE.dbo.invMarketGroups as t2
INNER JOIN marketparent as mp
ON mp.marketGroupID = t2.parentGroupID
)

-- Statement using the CTE

SELECT TOP 10 *
FROM marketparent;

最佳答案

你没有指定你的 DBMS,所以我假设 PostgreSQL

WITH RECURSIVE fam_tree (id, name, parent, family) as 
(
SELECT id,
name,
parentid,
''::text as family
FROM the_unknown_table
WHERE parent IS NULL

UNION ALL

SELECT t2.id,
t2.name,
t2.parentid,
fam_tree.family || '^' || t2.name
FROM the_unknown_table t2
INNER JOIN fam_tree ON fam_tree.id = t2.parentid
)
SELECT *
FROM fam_tree;

这是标准的 SQL(除了 ::text 类型转换),在大多数现代 DBMS 上几乎不需要改动。

编辑 :

对于 SQL Server,您需要将标准的串联字符替换为 Microsoft 的非标准 + (并且您需要删除标准要求的 recursive 关键字,但由于某些奇怪的原因被 SQL Server 拒绝)
WITH fam_tree (id, name, parent, family) as 
(
SELECT id,
name,
parentid,
'' as family
FROM the_unknown_table
WHERE parent IS NULL

UNION ALL

SELECT t2.id,
t2.name,
t2.parentid,
fam_tree.family + '^' + t2.name
FROM the_unknown_table t2
INNER JOIN fam_tree ON fam_tree.id = t2.parentid
)
SELECT *
FROM fam_tree;

关于sql-server - 如何在 SQL 中的单个列中显示递归 parentID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10176610/

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