PostgreSQL中支持多種類型的數據類型,其中數組類型在pg中也是被頻繁使用的一種,我們可以定義某列爲變長多維數組。
那麼對於不同數組我們怎麼獲取數組的交集,進行去除交集等操作呢?
對於字符串,我們可以使用except來直接進行去除交集,那麼數組該怎麼辦呢?
對於數組的去除交集我們的思路大致爲:
1、先把數組轉換成字符串;
2、將字符串的元素拆分然後進行去除交集;
3、將獲得的字符串轉換成數組。
例子:
我們使用上述的思路來將[1,2,3,4,5]和[2,3]這兩個數組進行去除交集。
1、數組轉換字符串
bill=# select array_to_string(array[1,2,3,4,5],',');
array_to_string
-----------------
1,2,3,4,5
(1 row)
2、拆分字符串
bill=# select regexp_split_to_table(array_to_string(array[1,2,3,4,5],',') ,',');
regexp_split_to_table
-----------------------
1
2
3
4
5
(5 rows)
3、對拆分的元素進行去除交集
bill=# select regexp_split_to_table(array_to_string(array[1,2,3,4,5],',') ,',') except select regexp_split_to_table(array_to_string(array[2,3],','),',');
regexp_split_to_table
-----------------------
4
5
1
(3 rows)
4、將去除交集後的字符串轉換成數組
bill=# select array(select regexp_split_to_table(array_to_string(array[1,2,3,4,5],',') ,',') except select regexp_split_to_table(array_to_string(array[2,3],','),','));
array
---------
{4,5,1}
(1 row)
參考鏈接:
https://www.postgresql.org/docs/12/arrays.html
https://www.postgresql.org/docs/12/functions-array.html