gpt4 book ai didi

sql - 在同一表中使用父 ID 选择父名称

转载 作者:行者123 更新时间:2023-11-29 13:12:20 25 4
gpt4 key购买 nike

我有一个带有 tag_categories 的表,我正在将它与其他一些表连接起来,这样我就可以获得文件标签的类别,在该表中我有一个 parent_id 列,它只是同一个表中的另一个标签类别。在构建如下查询时,它确实检索了 parent_id,但我不知道如何获取父名称:

查询:

select 
tags.id,
tags.name,
tag_categories.name,
tag_categories.parent_id,
count(files.id)
from
"files"
inner join "file_tags_join" on "files"."public_id" = "file_tags_join"."file_public_id"
inner join "tags" on "file_tags_join"."tag_id" = "tags"."id"
inner join "tag_categories" on "tags"."category_id" = "tag_categories"."id"
where
"tags"."category_id" is not null
group by
tags.id,
tags.name,
tag_categories.name,
tag_categories.parent_id

除了我已经得到的,我期望得到的是与类别的 parent_id 匹配的类别名称:

id  name    name    parent_id   count   parent_name
2 tag2 tagCategory2 1 1 tagCategory1
1 tag1 tagCategory1 (null) 1 null

这是 sql fiddle :

最佳答案

你可以试试下面

DEMO

select 
tags.id,
tags.name,
tag_categories.name,
tag_categories.parent_id,
b.name as parentname,
count(files.id)
from
"files"
inner join "file_tags_join" on "files"."public_id" = "file_tags_join"."file_public_id"
inner join "tags" on "file_tags_join"."tag_id" = "tags"."id"
inner join "tag_categories" on "tags"."category_id" = "tag_categories"."id"
left join "tag_categories" b on tag_categories.parent_id = b.id
where
"tags"."category_id" is not null
group by
tags.id,
tags.name,
tag_categories.name,
tag_categories.parent_id,b.name

输出:

id  name    name         parent_id  parentname  count
2 tag2 tagCategory2 1 tagCategory1 1
1 tag1 tagCategory1 1

关于sql - 在同一表中使用父 ID 选择父名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53317394/

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