這篇文章主要介紹了postgresql 實(shí)現(xiàn)將數(shù)組變?yōu)樾械牟僮?,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧。
有的時(shí)候需要把數(shù)組元素同表中的字段進(jìn)行關(guān)系運(yùn)算,首先得把a(bǔ)rray變?yōu)橛涗浶?/p>
SELECT "unnest"(array[1,2,3])
結(jié)果:
unnest
求數(shù)組交集:
SELECT "unnest"(array[1,2,3]) INTERSECT SELECT "unnest"(array[3,4,5])
結(jié)果:
unnest
3
補(bǔ)充:PostgreSQL單列多行變一行&一行變多行
工作中經(jīng)常遇到這樣一個(gè)場景,希望將某個(gè)字?jǐn)嗖樵兂龅媒Y(jié)果組合成為一個(gè)字符串,用逗號(hào)分割(或者分號(hào)),通過PG中的函數(shù)該如何實(shí)現(xiàn)?
多行變一行
實(shí)例表:

想要的結(jié)果:

方法一:string_agg(字段名,分隔符)
select id,string_agg(name,',') AS NAME_NEW from test
group by 1
ORDER BY 1
方法二:array_agg(字段名)
select id,array_agg(name)
AS NAME_NEW from test
group by 1
ORDER BY 1;
select id,array_to_string(array_agg(name),',')
AS NAME_NEW from test
group by 1
ORDER BY 1;
另外:array_agg(distinct(字段名)) 拼接唯一的字段。
一行變多行
select id,regexp_split_to_table(name_new,',')
AS NAME from test;
select id,unnest(string_to_array(name_new,','))
AS NAME from test;
文章來源:腳本之家
來源地址:https://www.jb51.net/article/204927.htm
申請創(chuàng)業(yè)報(bào)道,分享創(chuàng)業(yè)好點(diǎn)子。點(diǎn)擊此處,共同探討創(chuàng)業(yè)新機(jī)遇!