2013-02-25 67 views
2

只有非匹配元素的最佳方式是什么我迄今发现的是什么是找到两个字符串数组之间的PostgreSQL

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

我们可以做到这一点发现只有两个字符串数组之间的不匹配的元素。

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

喜欢整数数组,我们可以做到这一点

SELECT int[1,2,3] - int[2,3] 
+0

你的逻辑是错误的。结果应该是(a,b,d,e)不仅(a,b)。 – 2013-02-25 13:11:06

回答

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 
+0

我会怀疑(从问题)的原始声明更有效率。 – 2013-02-25 13:13:55

+0

@a_horse。是的,如果没有错的话。运行并比较。 – 2013-02-25 13:14:46

+0

啊!现在我看到它:) – 2013-02-25 13:16:49

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()需要被用作Clodo阿尔内托为已完成(而不是使用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; 
相关问题