2013-03-17 69 views
24

我試圖讓下面的返回計數使用左每個組織參加PostgreSQL的計數返回行,但我想不通爲什麼它不工作:查詢與LEFT JOIN不爲0

select o.name as organisation_name, 
     coalesce(COUNT(exam_items.id)) as total_used 
    from organisations o 
    left join exam_items e on o.id = e.organisation_id 
    where e.item_template_id = #{sanitize(item_template_id)} 
    and e.used = true 
    group by o.name 
    order by o.name 

使用​​3210似乎不起作用。我在智慧的結尾!任何幫助肯定會感激!

要澄清什麼是不起作用的,目前查詢只返回具有大於0的計數的組織的值。我希望它返回一個的行,每組織,不管計數如何。

表定義:

TABLE exam_items 
    id serial NOT NULL 
    exam_id integer 
    item_version_id integer 
    used boolean DEFAULT false 
    question_identifier character varying(255) 
    organisation_id integer 
    created_at timestamp without time zone NOT NULL 
    updated_at timestamp without time zone NOT NULL 
    item_template_id integer 
    stem_id integer 
    CONSTRAINT exam_items_pkey PRIMARY KEY (id) 

TABLE organisations 
    id serial NOT NULL 
    slug character varying(255) 
    name character varying(255) 
    code character varying(255) 
    address text 
    organisation_type integer 
    created_at timestamp without time zone NOT NULL 
    updated_at timestamp without time zone NOT NULL 
    super boolean DEFAULT false 
    CONSTRAINT organisations_pkey PRIMARY KEY (id) 
+1

'聚結處理NULL值(COUNT(exam_items.id),0)作爲total_used' ??? – wildplasser 2013-03-17 23:40:13

+0

好吧,我也試過COUNT(exam_items.id)作爲total_used,但是我不得不說sql並不是我的特長! – mulus 2013-03-17 23:47:40

+0

對不起,我明白你的意思了!我已經嘗試過了,但仍然沒有運氣:/ – mulus 2013-03-17 23:53:40

回答

42

這應該工作:

SELECT o.name AS organisation_name 
    , COUNT(e.id) AS total_used 
FROM organisations o 
LEFT JOIN exam_items e ON e.organisation_id = o.id 
         AND e.item_template_id = #{sanitize(item_template_id)} 
         AND e.used = true 
GROUP BY o.name 
ORDER BY o.name; 
  • 你有一個LEFT JOIN但後來WHERE條件迫使它是純JOIN
    將條件向下拉入JOIN子句,使其按預期工作。通過這種方式,只有滿足所有這些條件的行纔會被加入(或者左側的列被NULL填充)。否則(像你一樣),連接的行進行測試的附加條件(實際上LEFT [OUTER] JOIN),並從結果中刪除,如果他們不通過,就像一個普通的[INNER] JOIN

  • COUNT()永遠不會返回NULL開頭。在這方面,這是總體職能中的一個例外。因此, COALESCE(COUNT(col)) 從來沒有是有道理的,即使有額外的參數。 Per documentation

    應當指出的是,除了count,當選擇沒有行這些函數返回一個空值。

大膽強調我的。

+0

啊,很好!我錯過了exam_items上額外的where-clause元素... – wildplasser 2013-03-18 00:38:17

+3

ERWIN你是我的英雄!非常感謝! – mulus 2013-03-18 00:44:32

+0

@wildplasser:那一個已經錯過了最好的。這是一個鬼祟的。 – 2013-03-18 00:45:10

7

要清楚,

重要線是GROUP BY MAIN_TABLE將從SOME_TABLE

SELECT COUNT(ST.ID) 
FROM MAIN_TABLE MT 
LEFT JOIN SOME_TABLE ST ON MT.ID = ST.MT_ID 

GROUP BY MT.ID