sql - 比较 PostgreSQL 中两个逗号分隔的列

标签 sql arrays postgresql

我有两个表,其中一列包含以逗号分隔的数据。我需要比较两列。逗号分隔的字段可以按任何顺序排列,但顺序无关紧要。

create table x_a (id1 integer, shared text);
create table x_b (id1 integer, shared text);

insert into x_a values 
  (1, 'A,B,C,D,E')
, (2, 'A,B,C,D,E');

insert into x_b values 
  (1, 'B,A,C,E,D')
, (2, 'B,A,C,E');

我使用了下面的查询,但它没有返回任何输出:

select a.id1,b.id1, a.shared, b.shared
from x_a a ,x_b b
where a.id1 = b.id1 
and regexp_split_to_array(LOWER(a.shared),',')
  = regexp_split_to_array(LOWER(b.shared),',')

我不能使用运算符 &&,因为它会返回 id=2,这是错误的,因为“共享”列不是准确的副本。

最佳答案

I cannot use the operator && as it will return id=2 which is wrong ...

但您可以使用 array operators @> and <@ 像这样:

SELECT id1, a.shared AS a_shared, b.shared AS b_shared
FROM   x_a a
JOIN   x_b b USING (id1)
WHERE  string_to_array(a.shared, ',') @> string_to_array(b.shared, ',')
AND    string_to_array(a.shared, ',') <@ string_to_array(b.shared, ',');

如果 A 包含 B,而 B 包含 A,则两者相等 - 忽略重复项。

您可能希望首先存储(排序的)数组 - 或者使用 1:n 关系规范化您的数据库设计。

如果你的元素是integer数字,请考虑额外的 intarray 模块以获得卓越的性能。见:

关于sql - 比较 PostgreSQL 中两个逗号分隔的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55238337/

相关文章:

sql - 如何查询 MySQL JSON 列数据的空值?

mysql - for循环和mysql Node 如何等待所有查询完成才能处理 View

javascript - 从数组子元素的父元素创建一个新数组

C++ 数组运算符开销

java - 如何将字符串转换为 GUID

sql - 抓取用户IP地址信息进行审计

php - 从mysql中的当前日期获取过去的所有7个日期

mysql - SQL语句MySQL

installation - 通过 Psql 在 Firefox 中访问 Postgres

database - Postgres - 在应用程序之间共享数据集