我试图让下面的返回计数使用左每个组织参加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