[英]Use coalesce to return first non-empty value from 2 tablea
I have 2 tables in my Postgres db.我的 Postgres 数据库中有 2 个表。 Each of them has a URL column that I want to query and return the first non-empty value.
他们每个人都有一个 URL 列,我想查询并返回第一个非空值。 Table
桌子
test1
id name url
test2
id address url
I have the id
as an input.我有
id
作为输入。 How can I write a query to coalesce the latest available url for any 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
After the coalesce I expect return.com to be returned for id = 1
By latest available URL I mean the first non-null entry.在合并之后,我希望 return.com 返回
id = 1
最新可用的 URL 我的意思是第一个非空条目。
From the comments, it's hard to determine what "latest" and "first" mean, as COALESCE
does not know how to distinguish that (basically, you have to define the priority).从评论中,很难确定“最新”和“第一”的含义,因为
COALESCE
不知道如何区分(基本上,您必须定义优先级)。 If your example seeks return.com
, then the proper syntax is:如果您的示例寻求
return.com
,那么正确的语法是:
SELECT COALESCE(b.url,a.url) FROM test_1 a JOIN test2 a ON a.id=b.id WHERE a.id=1
So in this example, you will always show b.url
as long as it is not null.因此,在此示例中,只要不是 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 experts show off their chops here) 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专家在这里炫耀他们的印章)
Disclosure: I work for EnterpriseDB (EDB)披露:我为EnterpriseDB (EDB)工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.