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

时间:2018-11-15 10:31:14

标签: sql postgresql hierarchical-data

我有一个带有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

1 个答案:

答案 0 :(得分:1)

您可以在下面尝试

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