2015-05-18 58 views
0

我正在研究Postgres 9.3。我有兩個表,第一個支付項目:Postgres:如何加入

    Table "public.prescription" 
     Column  |   Type   |        Modifiers 
-------------------+-------------------------+-------------------------------------------------------------------- 
id    | integer     | not null default nextval('frontend_prescription_id_seq'::regclass) 
presentation_code | character varying(15) | not null 
presentation_name | character varying(1000) | not null 
actual_cost  | double precision  | not null 
pct_id   | character varying(3) | not null 

,第二個機構:

  Table "public.pct" 
     Column  |   Type   | Modifiers 
-------------------+-------------------------+----------- 
code    | character varying(3) | not null 
name    | character varying(200) | 

我有一個查詢,以獲得特定代碼的所有支付:

SELECT sum(actual_cost) as total_cost, pct_id as row_id 
FROM prescription 
WHERE presentation_code='1234' GROUP BY pct_id 

這是該查詢的query plan

現在,我想用相關組織的name屬性對每行進行註釋。這是我想要的:

SELECT sum(prescription.actual_cost) as total_cost, prescription.pct_id, pct.name as row_id 
FROM prescription, pct 
WHERE prescription.presentation_code='0212000AAAAAAAA' 
GROUP BY prescription.pct_id, pct.name; 

這是。這非常慢:我做錯了什麼?

我認爲在第一個查詢運行後,必須有一種方法用pct.name註釋每一行,這會更快。

+2

您還沒有加入的。請參閱有關如何執行此操作的手冊:http://www.postgresql.org/docs/current/static/tutorial-join.html和http://www.postgresql.org/docs/current/static/queries- table-expressions.html#QUERIES-FROM –

+0

Duh!謝謝。 – Richard

回答

2

隨着JOIN(LEFT JOIN在這種情況下,因爲我們希望即使沒有PCT線):

SELECT 
    sum(prescription.actual_cost) as total_cost, 
    prescription.pct_id, 
    pct.name as row_id 
FROM prescription 
    LEFT JOIN pct ON pct.code = prescription.pct_id 
WHERE 
    prescription.presentation_code='0212000AAAAAAAA' 
GROUP BY 
    prescription.pct_id, 
    pct.name; 

我不知道,如果它的工作很好,我沒有嘗試此查詢。

0

您正在從2個表中獲取數據,但不以任何方式加入表格。實際上,您可以完全加入,從而生成兩個表的笛卡爾積。如果你看看你的統計數據,你會發現你的嵌套循環處理了6200萬行。這需要時間。

添加一個連接條件,以使這一切快:

SELECT sum(prescription.actual_cost) as total_cost, prescription.pct_id, pct.name as row_id 
FROM prescription 
JOIN pct On pct.code = prescription.pct_id 
WHERE prescription.presentation_code = '0212000AAAAAAAA' 
GROUP BY prescription.pct_id, pct.name;