2013-02-25 42 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; 
相關問題