2013-06-12 53 views
2

直到大約5分鐘前,我甚至不知道你得到一個VARCHAR類型,它也是一個數組。我怎麼會加入這些表:加入類型爲「VarChar Array」的postgresql表?

PEOPLE 
ID | PERSON | GROUPS 
1 | John | {ONE,TWO} 
2 | Jack | {TWO} 
3 | Jill | {ONE,TWO,THREE} 
4 | Jim | {TWO,THREE} 

GROUPS 
ID | TITLE 
ONE | First 
TWO | Second 
THREE | Third 

我想用這樣的事情結束了:

ID | PERSON | GROUP 
1 | John | ONE 
1 | John | TWO 
2 | Jack | TWO 
3 | Jill | ONE 
3 | Jill | TWO 
3 | Jill | THREE 
4 | Jim | TWO 
4 | Jim | THREE 

我怎麼會得到一個查詢這個權利?

回答

2

對於特定的查詢,有使用unnest()語法技巧,這使得擴大單行爲多行時,它的SELECT語句的一部分:

select id, person, unnest(groups) as grp 
from people 

我猜你真正想要首先,第二,第三個出現而不是一個,兩個或三個,但是。你可以加入像這樣:

with unnested_people as (
select id, person, unnest(groups) as grp 
from people 
) 
select id, person, title 
from unnested_people 
join groups on groups.id = unseated_people.grp 
+1

無論誰降低了這一點,都應該真正測試並親眼看到語法技巧工作得很好,例如: 'select 1 as a,unnest('{2,3}':: int [])as b;' –

+0

絕對是我在找的! :) – coderama

+0

和一個非常酷的技巧(unnest)。 – coderama

6

unnest沒有必要在這裏,你可以使用與數組成員測試一個簡單連接:

SELECT people."ID", people."PERSON", groups."ID" 
FROM people 
INNER JOIN groups ON groups."ID" = ANY (people."GROUPS") 
ORDER BY people."ID", groups."ID"; 

參見:http://sqlfiddle.com/#!12/5fa34/7

(怪異的大寫因爲我無法修復SQLFiddle的不一致的標識符引用,它引用了列名但不包括表名)

Yo你甚至可以在people.GROUPS上使用GIN索引並獲得索引連接。 GIN指數的構建起來並不便宜,而且更新費用昂貴,所以只有在真正需要時才需要這樣做,但這很有用。請參閱數組索引手冊。例如:

CREATE INDEX people_groups_gin_idx ON people USING GIN("GROUPS"); 

SELECT people."ID", people."PERSON", groups."ID" 
FROM people 
INNER JOIN groups ON ARRAY[groups."ID"] @> people."GROUPS" 
ORDER BY people."ID", groups."ID"; 
相關問題