[英]Use coalesce to return first non-empty value from 2 tablea
我的 Postgres 数据库中有 2 个表。 他们每个人都有一个 URL 列,我想查询并返回第一个非空值。 桌子
test1
id name url
test2
id address url
我有id
作为输入。 如何编写查询以合并任何 id 的最新可用 url?
test 1
ID name url
1 A null
2 B abc.com
3 C xyz.com
test 2
ID address url
1 X return.com
2 Y null
3 Z efg.com
在合并之后,我希望 return.com 返回id = 1
最新可用的 URL 我的意思是第一个非空条目。
从评论中,很难确定“最新”和“第一”的含义,因为COALESCE
不知道如何区分(基本上,您必须定义优先级)。 如果您的示例寻求return.com
,那么正确的语法是:
SELECT COALESCE(b.url,a.url) FROM test_1 a JOIN test2 a ON a.id=b.id WHERE a.id=1
因此,在此示例中,只要不是 null,您将始终显示b.url
。 If you want it to dynamically prioritize a.url
and b.url
based on some time-based criteria, you'll need to write a plpgsql
function or do some convoluted array nesting and string concatenation (or I'd want to see some other专家在这里炫耀他们的印章)
披露:我为EnterpriseDB (EDB)工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.