Postgresql 是否可以使用基于列';的子查询获取列值;钥匙是什么?

Postgresql 是否可以使用基于列';的子查询获取列值;钥匙是什么?,postgresql,subquery,lateral-join,Postgresql,Subquery,Lateral Join,我有下表: 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 pi

我有下表:

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
select id, 
       coalesce(fruit, (select t2.fruit
                        from the_table t2
                        where t2.id = t1.parent
                        limit 1)) as fruit
from the_table t1

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

id_1 apple
id_3 pineapple
id_4 plum
select id, 
       coalesce(fruit, (select t2.fruit
                        from the_table t2
                        where t2.id = t1.parent
                        limit 1)) as fruit
from the_table t1

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

id_1 apple
id_3 pineapple
id_4 plum
select id, 
       coalesce(fruit, (select t2.fruit
                        from the_table t2
                        where t2.id = t1.parent
                        limit 1)) as fruit
from the_table t1

您可以这样做:

id_1 apple
id_3 pineapple
id_4 plum
select id, 
       coalesce(fruit, (select t2.fruit
                        from the_table t2
                        where t2.id = t1.parent
                        limit 1)) as fruit
from the_table t1
编辑,抱歉,错过了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;

您可以这样做:

id_1 apple
id_3 pineapple
id_4 plum
select id, 
       coalesce(fruit, (select t2.fruit
                        from the_table t2
                        where t2.id = t1.parent
                        limit 1)) as fruit
from the_table t1
编辑,抱歉,错过了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;

@一匹没有名字的马,是的,谢谢你指出它是Postgres而不是MySQL。更新我的answer@a_horse_with_no_name,是的,谢谢你指出这是Postgres而不是MySQL。更新了我的答案