到目前为止我发现的是
select ARRAY(
select unnest(ARRAY[ 'a', 'b', 'c' ])
except
select unnest(ARRAY[ 'c', 'd', 'e' ])
)
我们可以这样做,只找到两个字符串数组之间的非匹配元素。
还有其他最好的办法吗?
与整数数组一样,我们可以这样做
SELECT int[1,2,3] - int[2,3]
答案 0 :(得分: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
答案 1 :(得分: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;