2015-11-01 70 views
2

假設我有以下表格:Postgres的JOIN與UNNEST

table: followers_arrays 

    id | array 
--------+--------- 
    1 | {3,4,5} 


table: small_profiles 

    id | username | pic  
--------+----------+------- 
    3 | aaaa | abcd 
    4 | bbbb | abcd 
    5 | cccc | abcd 

我想使用簡單連接打印followers_array與填充的數據來自small_profiles

起初,我使用UNNEST功能是這樣的:

SELECT id, unnest(followers_array) AS elem FROM followers_arrays 

,這讓我對正確的結果:現在

id | elem 
--------+-------- 
    1 | 3 
    1 | 4 
    1 | 5 

,從我的理解,我只需要加入這個數據到small_profiles ON small_profiles.id這樣的鍵:

SELECT id, unnest(followers_array) AS elem 
FROM followers_arrays 
JOIN small_profiles ON small_profiles.instagram_id = elem 

但是似乎在JOIN,列ELEM因爲我碰到下面的錯誤不會創建尚未: 錯誤:列「ELEM」不存在

任何想法,我應該如何重新安排我的查詢? 感謝

回答

1

這是不好的設計,但這裏是你的答案:

select f.id, f.follower, s.username, s.pic 
from 
    (
     select id, unnest("array") as follower 
     from followers_arrays 
    ) f 
    inner join 
    small_profiles s on f.follower = s.id 
+1

作品!你能告訴我爲什麼這是不好的設計? –

+0

@Rafal沒有理由擁有一個數組。簡單的標準化會更好。 –

+0

@ClodoaldoNeto爲什麼普通標準化會更好? – Roshambo

0

我更喜歡子查詢使用公用表表達式:

WITH unnested_arr_1 AS (
    SELECT unnest(ARRAY[1, 2, 3]) array_1_item 
) 
,unnested_arr_2 AS (
    SELECT unnest(ARRAY[2, 3, 4]) array_2_item 
) 
SELECT * 
FROM unnested_arr_1 arr1 
    FULL OUTER JOIN unnested_arr_2 arr2 ON arr1.array_1_item=arr2.array_2_item 

生產:

array_1_item |array_2_item | 
-------------|-------------| 
1   |[NULL]  | 
2   |2   | 
3   |3   | 
[NULL]  |4   |