【问题标题】:Postgresql Select a column or other under the same alias according to the value of a third columnpostgresql 根据第三列的值选择同一别名下的一列或其他
【发布时间】:2021-12-26 19:14:27
【问题描述】:

我有一个数据库,其架构可以通过这种方式简化:一个产品表和两个包含值的表,以丰富产品的描述。我想做一个 SELECT 查询,允许我显示产品 id,后跟一个包含值的列。 如果产品类型为“Type1”,则可以在attribute_value_1 表中选择该值;如果产品类型为“Type2”,则可以在attribute_value_2 表中选择。

餐桌产品

product_id type
1 type1
2 type2

表属性值_1

id product_id value
1 1 XXXXX

表属性值_2

id product_id value
1 2 ZZZZZ

所以在下面的例子中,查询的结果应该是:

结果

product_id value
1 XXXXX
2 ZZZZZ

你知道我该怎么做吗?

【问题讨论】:

    标签: sql postgresql select case


    【解决方案1】:

    你可以对每个属性表使用两个左连接,然后使用 coalesce() 函数,从那些匹配的表中获取值:

    select P.product_id , coalesce(att1.value, att2.value) value
    from product p 
    left join attribute_value_1 att1
       on p.product_id = att1.product_id and p.type = 'type1'
    left join attribute_value_1 att2
       on p.product_id = att2.product_id and p.type = 'type2'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-07
      • 2022-09-30
      • 1970-01-01
      • 2018-09-24
      • 1970-01-01
      • 2023-03-19
      • 2022-01-23
      相关资源
      最近更新 更多