通过连接自己从一个表中选择默认值

时间:2017-06-19 11:47:58

标签: sql postgresql

例如,我在t_shops中有一个表和3个 NOT NULL 列:id,name,locale。 Locale列的默认值为“”空字符串。我需要选择默认值,如果where语句不匹配 AND 我需要通过连接相同的表并传递给COALESCE函数来做到这一点。我知道如何通过COEREESCE在WHERE子句和UNION ALL中做到这一点,但我需要加入

SELECT COALESCE(arg1.locale, 'default') currentLocale
    ,A.*
FROM t_product_attrs A
INNER t_product_attrs arg1
    ON A.locale = arg1.locale
        AND A.product_id = arg1.product_id
WHERE arg1.locale = 'not what i have in DB'
    AND arg1.product_id = 100101

1 个答案:

答案 0 :(得分:1)

我想你想要一个left join

SELECT COALESCE(arg1.locale, 'default') as currentLocale, A.*
FROM t_product_attrs A INNER
     t_product_attrs arg1
     ON A.locale = arg1.locale AND
        A.product_id = arg1.product_id  AND
        arg1.locale = 'not what i have in DB' AND
        arg1.product_id = 100101;