[英]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.