如果WHERE语句不匹配,请从非空列中选择默认值

时间:2017-06-13 14:45:57

标签: postgresql expression conditional-statements

例如,我在t_shops中有3个NOT NULL列:id,name,locale。区域设置列的默认值为" "空字符串。如果where语句不匹配,我需要选择默认值。我尝试使用COALESCE函数,但它只适用于NULL列。我有PostgreSQL DB。

SELECT locale FROM t_shops WHERE id = '123' locale = 'not what i have in DB'

1 个答案:

答案 0 :(得分:0)

LIMIT 1

SELECT locale 
FROM t_shops 
WHERE id = '123' AND locale = 'not what i have in DB' 
UNION ALL 
SELECT 'default locale goes here' 
LIMIT 1 ;  -- t_shops.locale if available, else default

COALESCE + SUBSELECT

SELECT COALESCE(  
  ( SELECT locale  
    FROM t_shops   
    WHERE id = '123' AND locale = 'not what i have in DB'  
    -- LIMIT 1, if required; depends on UNIQUE (locale) or not  
  ),  
  'default locale goes here' -- 'default'::locale with type possible  
);

对评论的回应

实际上,我不知道如何回复你的评论,因为我不知道你想做什么。

您能否发布product表的表格架构? 像这样:

CREATE TABLE product (id SERIAL PRIMARY KEY, 
                      locale TEXT NOT NULL, 
                      other_column INT NOT NULL);

用正常的英语单词描述你想做什么。 也许你甚至不需要LEFT JOIN两次到同一张桌子......