2015-11-02 65 views
5

我有這樣一個表如何在Postgres中按數組列排列結果?

id SERIAL, 
user_id INT, 
community_id INT[], 

的桌上擺滿這樣:

id | user_id | community_id 
1 | 1  | {2, 4} 
2 | 5  | {2, 5} 
3 | 10  | {2, 4} 

我想獲得每個社區有用戶COUNT,community_id是陣列的Cuz用戶可以在幾個社區在同一時間。

查詢應該是簡單的:

SELECT community_id, COUNT(user_id) FROM tbl GROUP BY community_id 

結果應該是這樣的:

community_id | user_count 
2    | 3 
4    | 2 
5    | 1 

我不知道數組如何GROUP BY列。有誰能夠幫助我 ?

+3

該查詢將作爲簡單如您所願,如果模型正常化。 –

+0

你能更具體嗎? –

+0

你有一個古典的一對多關係。這不應該用一個數組來表示,而應該用兩個表來表示。 https://en.wikipedia.org/wiki/Database_normalization#Example –

回答

9

您可以使用unnest()得到的數據歸一化視圖,並總:

select community_id, count(*) 
from (
    select unnest(community_id) as community_id 
    from tbl 
) t 
group by community_id 
order by community_id; 

但你確實應該解決您的數據模型。

+0

很好的答案!不知道不知道 – Matt

0
select unnest(community_id) community_id 
     ,count(user_id) user_count 
from table_name 
group by 1 --community_id = 1 and user_count = 2 (index of a column in select query) 
order by 1 -- 

sqlfiddle


unnest(anyarray)展開陣列,以一組行

select unnest(ARRAY[1,2])會給

unnest 
    ------ 
     1 
     2