gpt4 book ai didi

sql - 如何在 SQL Server 中使用自连接在单个表上映射子父项?

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

我有下表与子父关系。

ID      Title               PageID  IsParent    ParentID    IsActive
1 Dashboard 2125 True NULL True
2 Site Analytics 22 False NULL True
3 SEO Management 1 NULL NULL True
4 Mail Management 32 NULL NULL True
5 Build Mobile App 3214 NULL NULL True
6 Market Analytics 1321 NULL NULL True
7 Customize 235345 NULL NULL True
8 Reporter 253 NULL NULL True
9 Editor 545 NULL NULL True
10 News Template 45 NULL NULL True
11 Test Menu 0 True 3 True
NULL NULL NULL NULL NULL NULL

这里的ParentID定义了父子关系。例如,在上表中,Test MenuSite Analytics 的子项。我有以下 SQL 查询。

SELECT
P.ID
,P.Title AS Parent
,C.Title AS Child
,P.PageID
,P.IsParent
,P.ParentID
,P.IsActive
FROM [dbo].[ChildParent] P
LEFT JOIN [dbo].[ChildParent] C ON P.ID = C.ParentID

输出结果如下。

1   Dashboard           NULL            2125    1       NULL    1
2 Site Analytics NULL 22 0 NULL 1
3 SEO Management Test Menu 1 NULL NULL 1
4 Mail Management NULL 32 NULL NULL 1
5 Build Mobile App NULL 3214 NULL NULL 1
6 Market Analytics NULL 1321 NULL NULL 1
7 Customize NULL 235345 NULL NULL 1
8 Reporter NULL 253 NULL NULL 1
9 Editor NULL 545 NULL NULL 1
10 News Template NULL 45 NULL NULL 1
11 Test Menu NULL 0 1 3 1

基本上,我想要实现的是:

1   Dashboard           NULL            2125    1       NULL    1
2 Site Analytics NULL 22 0 NULL 1
3 SEO Management NULL 1 NULL NULL 1
4 Mail Management NULL 32 NULL NULL 1
5 Build Mobile App NULL 3214 NULL NULL 1
6 Market Analytics NULL 1321 NULL NULL 1
7 Customize NULL 235345 NULL NULL 1
8 Reporter NULL 253 NULL NULL 1
9 Editor NULL 545 NULL NULL 1
10 News Template NULL 45 NULL NULL 1
11 Test Menu SEO Management 0 1 3 1

最佳答案

在您的查询中尝试这个小改动:

SELECT
P.ID
,P.Title AS Parent
,C.Title AS Child
,P.PageID
,P.IsParent
,P.ParentID
,P.IsActive
FROM [dbo].[ChildParent] P
LEFT JOIN [dbo].[ChildParent] C ON isnull(P.ParentID, P.ID) = c.id and C.ParentID is not null

关于sql - 如何在 SQL Server 中使用自连接在单个表上映射子父项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47614938/

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