我試圖讓下面的返回計數使用左每個組織參加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)
'聚結處理NULL值(COUNT(exam_items.id),0)作爲total_used' ??? – wildplasser 2013-03-17 23:40:13
好吧,我也試過COUNT(exam_items.id)作爲total_used,但是我不得不說sql並不是我的特長! – mulus 2013-03-17 23:47:40
對不起,我明白你的意思了!我已經嘗試過了,但仍然沒有運氣:/ – mulus 2013-03-17 23:53:40