PostgreSQL数组如何去除交集

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

猜你喜欢

转载自blog.csdn.net/weixin_39540651/article/details/106973268
今日推荐