gpt4 book ai didi

sql - 类别和子类别数据库

转载 作者:行者123 更新时间:2023-12-04 20:12:39 24 4
gpt4 key购买 nike

我在检索列值时遇到问题,例如取决于其他列
我试图用外连接和嵌套选择来做,但我想我无法在脑海中找到解决方案

Categories Table:
ID Name ParentID
--------------------------------
1 Software NULL
2 Domains NULL
3 Games NULL
4 Accounts NULL
5 Others NULL
6 Security Software 1
7 Operating Systems 1
8 Browsers 1
9 Developer Tools 1
10 .com Domains 2
11 .net Domains 2
12 .org Domains 2
13 Online Games 3
14 PC Games 3
15 PS Games 3
16 RapidShare Accounts 4
17 4shared Account 4
18 Web Templates 5
19 Flash Intros 5
20 Firewall 6
21 Antivirus 6

我想要做什么来显示父类别名称
而不是 parentID

像那样
ID  Name                ParentID
--------------------------------
1 Software NULL
2 Domains NULL
3 Games NULL
4 Accounts NULL
5 Others NULL
6 Security Software Software
7 Operating Systems Software
8 Browsers Software
9 Developer Tools Software
10 .com Domains Domains
11 .net Domains Domains
12 .org Domains Domains
13 Online Games Games
14 PC Games Games
15 PS Games Games
16 RapidShare Accounts Accounts
17 4shared Account Accounts
18 Web Templates Others
19 Flash Intros Others
20 Firewall Security Software
21 Antivirus Security Software

最佳答案

你需要在 table 上加入两次

SELECT c1.Id, c1.Name as parentname , c2.name
FROM categories c1
JOIN categories c2
ON c1.id = c2.parentid

结果将是:
ID      ParentName            Name
1 software security software
1 software operating software
2 domains .com domains
2 domains .net domains
2 domains .org domains
3 games pc games

这将为您提供子类别或子类别的 parentID、parentName 和 Name。

如果需要,您还可以更改它以包含子类别 ID。

根据您的编辑,您可以使用以下内容:
create table categories
(
id int,
name varchar(50),
parentid int
)

insert into categories values(1, 'software', null)
insert into categories values(2, 'domains', null)
insert into categories values(3, 'games', null)
insert into categories values(6, 'security software', 1)
insert into categories values(7, 'operating systems', 1)
insert into categories values(8, 'browsers', 1)
insert into categories values(10, '.com domains', 2)
insert into categories values(11, '.net domains', 2)
insert into categories values(12, '.org domains', 2)
insert into categories values(13, 'online games', 3)
insert into categories values(14, 'pc games', 3)
insert into categories values(15, 'ps games', 3)

select c1.id
, c1.name
, (select name from categories where c1.parentid = categories.id) as ParentId
from categories c1

这将导致:

enter image description here

关于sql - 类别和子类别数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10453871/

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