sql - PostgreSQL : check if value is in 2 columns and remove it from one of them

标签 sql arrays postgresql

我有两列 indtar,它们都包含数组。

 ind      tar
{10}      {10}
{6}       {5,6}
{4,5,6}   {5,6}
{5,6}     {5,6}
{7,8}     {11}
{11}      {5,6,7}
{11}      {8}
{9,10}    {6}

我想查找两个数组中是否都存在一个值,如果是这样,我只想将其保留在 ind 列中。例如,在第一行,两列中的值均为 10。我希望仅在 ind 列中得到该值,并将 tar 列留空。这是预期的结果:

 ind      tar      
{10}      
{6}       {5}
{4,5,6}   
{5,6}     
{7,8}     {11}
{11}      {5,6,7}
{11}      {8}
{9,10}    {6}

如何在 PostgreSQL 中做到这一点?

到目前为止,我只找到了共同的元素,但我不知道如何继续将它们仅保留在 ind 列中并从 tar 列中删除它们.

with t1 as (
select distinct ind, tar
from table_1
join table_2 using (id) 
limit 50
),
t2 as (
select ind & tar as common_el, ind , tar 
from t1
)
select *
from t2

结果如下:

   common_el   ind        tar
    {10}      {10}       {10}
    {6}       {6}       {5,6}
    {5,6}     {4,5,6}   {5,6}
    {5,6}     {5,6}     {5,6}

最佳答案

你可以这样做(fiddle):

表创建:

CREATE TABLE t(x INTEGER[], y INTEGER[]);

填充表格:

INSERT INTO t VALUES
('{10}',      '{10}'),
('{6}',       '{5,6}'),
('{4,5,6}',   '{5,6}'),
('{5,6}',     '{5,6}'),
('{7,8}',     '{11}'),
('{11}',      '{5,6,7}'),
('{11}',      '{8}'), 
('{9,10}',    '{6}'),

--
-- records below added for testing!
--

('{11}',      '{5,8,10,11,133}'),  
('{9,10}',    '{4,5,6,8,9,10,11}'),
('{9,10}',    '{4,5,6,8,9,10,11}');

标准数组,UNNEST + EXCEPT ( fiddle ):

如果您不想或不能,请使用 INTARRAY .

SELECT 
  t.x,
  ARRAY((SELECT UNNEST(t.y)) EXCEPT (SELECT UNNEST(t.x))) 
FROM 
  t;

结果:

x   array
{10}    {}
{6} {5}
{4,5,6} {}
{5,6}   {}
{7,8}   {11}
{11}    {7,5,6}
{11}    {8}
{9,10}  {6}
{11}    {8,10,133,5}
{9,10}  {11,8,5,4,6}
{9,10}  {11,8,5,4,6}

Et voilà - 想要的结果!请参阅here一个优秀的线程,其中包含许多解决此问题的方法以及讨论的密切相关的问题!

关于sql - PostgreSQL : check if value is in 2 columns and remove it from one of them,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69853767/

相关文章:

mysql - 是否可以在 MySQL 中搜索和替换字符串数组?

mysql - 允许同一父级的多个 "types"数据的通用模式是什么

postgresql - 如何在 Postgres 中使用数组作为变量?

python - Postgres View 的 Django 模型

sql - Heroku 上的 Rails rake 任务 : Disable displaying the SQL log on the screen

php - PHP Documentor 中的注释关联数组

C - 合并排序的合并部分

python - 使用常量内存旋转 m 个位置左侧的 n 个元素的一维数组?

sql - 如何删除不能转换为 INT 的行

mysql - 如何在 mysql 中设置本地列表/元组变量