2016-06-08 48 views
1

我想打一個查詢如何使查詢array_agg與此SQL?

select * from projects where user_id = 3; 

,並根據它的結果r,我需要做n查詢,其中n長度rl。例如:

| id | project_name | description | user_id | 
| 1 | Project A | lorem ipsu | 3  | 
| 4 | Project B | lorem ipsu | 3  | 

l => 2然後

select * from images where project_id = 1; 
select * from images where project_id = 4; 

好吧,你可以看到這是怎麼回事,如果l太大。選擇太多,訪問數據庫太多。有沒有更好的方式來實現一個最終的結果,像這樣:

| id | project_name | description | user_id | images   | 
| 1 | Project A | lorem ipsu | 3  | {imgX,imgY,imgZ} | 
| 4 | Project B | lorem ipsu | 3  | {imgA,imgB}  | 

我聽到的Postgres約array_agg功能。也許這就是答案?不管怎麼說,這些都是我的表說明:

       Table "public.projects" 
    Column |   Type   |       Modifiers      
-------------+--------------------------+------------------------------------------------------- 
id   | integer     | not null default  nextval('projects_id_seq'::regclass) 
name  | character varying(255) | 
description | character varying(255) | 
user_id  | integer     | 
created_at | timestamp with time zone | 
updated_at | timestamp with time zone | 

            Table "public.images" 
    Column |   Type   |      Modifiers      
------------+--------------------------+----------------------------------------------------- 
id   | integer     | not null default nextval('images_id_seq'::regclass) 
name  | character varying(255) | 
url  | character varying(255) | 
project_id | integer     | 
created_at | timestamp with time zone | 
updated_at | timestamp with time zone | 

謝謝你提前:d

回答

1

array_agg是像任何其他集合函數(count,sum),但返回一個數組而不是標量值。您只需加入並分組兩個表即可實現您所需要的內容。

SELECT p.id, p.name, p.description, p.user_id, array_agg(i.name) images 
FROM projects p 
LEFT JOIN images i ON p.id = i.project_id 
GROUP BY p.id, p.name, p.description, p.user_id 
+0

解釋詢問太 –

+0

對不起,我認爲這很容易理解。編輯。 –

0

可能是你最簡單的解決方案是一個子選擇。這是最接近您在前面提到的個別SELECT聲明:

SELECT * FROM images 
WHERE project_id IN (
    SELECT project_id FROM projects 
    WHERE user_id = 3); 
0

你想在image names as array匹配從projects記錄加上記錄由project_id

SELECT * 
FROM projects 
LEFT JOIN LATERAL (SELECT array_agg(name) AS images FROM images WHERE project_id = projects.project_id) x ON true 
WHERE user_id = '3' 

sqlfiddle