【问题标题】:Is it posible to create hierarchy but with multiple rows in Postgres?是否可以在 Postgres 中创建层次结构但具有多行?
【发布时间】:2019-10-29 08:18:32
【问题描述】:

我可以用一行结果创建一个层次结构(使用来自我的previous question 的查询),但是当它有多行时我不知道从哪里开始。

这是我的桌子:

     id|  parent_id|                      name|
-------|-----------|--------------------------|
      1|     [NULL]|             United States|
      2|     [NULL]|                     Japan|
      3|          1|                  New York|
      4|          3|                  Brooklyn|
      5|          6|               Los Angeles|
      6|          1|                California|
      7|          6|                     Dixon|
      8|          2|                     Kyoto|
      9|          2|                     Tokyo|

name 具有 null parent_id 是祖父母。那么,如何查询产生这样的结果呢?

                   Country|    States/Province|           City|
|-------------------------|-------------------|---------------|
|            United States|           New York|       Brooklyn|
|            United States|         California|    Los Angeles|
|            United States|         California|          Dixon|
|                    Japan|              Kyoto|         [NULL]|
|                    Japan|              Tokyo|         [NULL]|

【问题讨论】:

    标签: sql postgresql hierarchical-data


    【解决方案1】:

    看起来像一个简单的表上的自连接,因为您感兴趣的级别数是有限的:

    select co.name as country,
           p.name as "State/Province", 
           ct.name as city
    from hierarchy co
      left join hierarchy p on p.parent_id = co.id
      left join hierarchy ct on ct.parent_id = p.id
    where co.parent_id is null
    order by co.name;
    

    在线示例:https://rextester.com/UON36358

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-06
      • 1970-01-01
      相关资源
      最近更新 更多