2

到目前为止我发现的是

select ARRAY(
   select unnest(ARRAY[ 'a', 'b', 'c' ])
   except
   select unnest(ARRAY[ 'c', 'd', 'e' ])
)

我们可以这样做以仅查找两个字符串数组之间的不匹配元素。

有没有其他最好的方法来做到这一点?

就像整数数组一样,我们可以这样做

SELECT int[1,2,3] - int[2,3]
4

2 回答 2

1
select array_agg(e order by e)
from (
    select e
    from
    (
        select unnest(array[ 'a', 'b', 'c' ])
        union all
        select unnest(array[ 'c', 'd', 'e' ])
    ) u (e)
    group by e
    having count(*) = 1
) s
于 2013-02-25T13:09:37.097 回答
1

这是另一种选择:

select ARRAY
(
   (
     select unnest(ARRAY[ 'c', 'd', 'e' ])
     except
     select unnest(ARRAY[ 'a', 'b', 'c' ])
   )
   union 
   (
     select unnest(ARRAY[ 'a', 'b', 'c' ])
     except
     select unnest(ARRAY[ 'c', 'd', 'e' ])
   )
);

或者(为了更清楚地说明涉及两个不同的数组):

with array_one (e) as (
   select unnest(ARRAY[ 'a', 'b', 'c' ])
), array_two (e) as (
   select unnest(ARRAY[ 'c', 'd', 'e' ])
)
select array(
   ( 
      select e from array_one
      except 
      select e from array_two
   )
   union 
   (
     select e from array_two
     except 
     select e from array_one
   )
) t;

如果元素的顺序很重要,那么 array_agg() 需要像 Clodoaldo Neto 一样使用(而不是使用array(...)构造函数):

with array_one (e) as (
   select unnest(ARRAY[ 'a', 'b', 'c' ])
), array_two (e) as (
   select unnest(ARRAY[ 'c', 'd', 'e' ])
)
select array_agg(e order by e)
from (
   ( 
      select e from array_one
      except 
      select e from array_two
   )
   union 
   (
     select e from array_two
     except 
     select e from array_one
   )
) t;
于 2013-02-25T13:18:16.447 回答