【问题标题】:Is it possible to get column value with subquery based on column's key?是否可以根据列的键使用子查询获取列值?
【发布时间】:2020-11-26 18:00:14
【问题描述】:

我有下表:

id   |     fruit |  parent |
----------------------------
id_1 |     apple |         |
id_2 |           |    id_3 |
id_3 | pineapple |         |
id_4 |      plum |    id_5 |
id_5 |      plum |         |

是否可以通过子查询/横向连接获得以下输出:

id_1 apple
id_2 pineapple
id_4 plum

因此,如果水果为空,则获取父母的水果。尝试使用子查询来获取此信息,收集链接的父母以从中获取水果值,但在这种情况下,这些值与他们的 ID 配对,而不是与“孩子”ID 配对。所以是这样的:

id_1 apple
id_3 pineapple
id_4 plum

【问题讨论】:

    标签: postgresql subquery lateral-join


    【解决方案1】:

    如果这只是一个级别,你可以这样做:

    select id, 
           coalesce(fruit, (select t2.fruit
                            from the_table t2
                            where t2.id = t1.parent
                            limit 1)) as fruit
    from the_table t1
    

    Online example

    【讨论】:

      【解决方案2】:

      你可以这样做:

      编辑,抱歉,错过了它是 postgres。这行得通

      SELECT t1.id, (CASE WHEN t1.parent is NULL THEN t1.fruit ELSE t2.fruit END) as fruit
      FROM fruits as t1
      LEFT JOIN fruits as t2 ON t1.parent = t2.id;
      

      【讨论】:

      • @a_horse_with_no_name,是的,感谢您指出它是 Postgres 而不是 MySQL。更新了我的答案
      猜你喜欢
      • 1970-01-01
      • 2023-03-08
      • 2016-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-19
      • 1970-01-01
      相关资源
      最近更新 更多