[英]Return deafult value in SQL select statment searched value is not found
I need to return default value in Select statement when WHERE clause is not met.当不满足 WHERE 子句时,我需要在 Select 语句中返回默认值。 So basically, this query returns valid guid:
所以基本上,这个查询返回有效的 guid:
SELECT COALESCE(w.guid , gen_random_uuid()) as guid
FROM MyTable w
WHERE w.id = 108
AND w.company IN (27);
But this doesn't find id 109, so it should generate new random uuid:但这没有找到 id 109,所以它应该生成新的随机 uuid:
SELECT COALESCE(w.guid , gen_random_uuid()) as guid
FROM MyTable w
WHERE w.id = 109
AND w.company IN (27);
But instead it returns nothing.但相反,它什么也不返回。 How I can solve this?
我该如何解决这个问题?
You get no uuid because no row is selected and nothing returned therefore.您没有 uuid,因为没有选择任何行,因此没有返回任何内容。 This might solve your problem:
这可能会解决您的问题:
SELECT coalesce(
(select w.guid FROM MyTable w
WHERE w.id = 109 AND w.company IN (27)
),
gen_random_uuid()) as guid;
Didn't test it on real data, but you get the idea i'm sure.没有在真实数据上对其进行测试,但我确定你明白了。
Use a RIGHT JOIN on a sub select that creates the default value.在创建默认值的子 select 上使用 RIGHT JOIN。 Something like this (not tested, no data available):
像这样的东西(未经测试,没有可用数据):
SELECT
COALESCE( w.guid, G.guid ) AS guid
FROM
genius."attribute" w
RIGHT JOIN ( SELECT gen_random_uuid()) G ( guid ) ON w.ID = 109 AND w.company IN ( 27 );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.