选择记录group_concat()包含char

时间:2016-02-18 08:15:58

标签: mysql group-concat

如何选择仅包含0

mystatus字段
select c.id,count(*),
       group_concat(distinct(r.status not in ('Done','None'))) as mystatus
from cases c inner join reports r 
on (c.id = r.parent_id and r.parent_type = 'Cases' and r.deleted = 0)
where c.deleted = 0 
and c. status <> 'Late'
group by c.id

结果如下所示,但我想仅选择mystatus包含0。

ID  count(*)  mystatus
A   1         0
B   7         0,1
C   2         0

应选择记录ID A和C

2 个答案:

答案 0 :(得分:1)

您必须使用HAVING子句:

select c.id,count(*),
       group_concat(distinct(r.status not in ('Done','None'))) as mystatus
from cases c inner join reports r 
on (c.id = r.parent_id and r.parent_type = 'Cases' and r.deleted = 0)
where c.deleted = 0 and c. status <> 'Late'
group by c.id
having count(case when r.status <> 0 then 1 end) = 0

HAVING子句的谓词使用条件聚合来过滤掉包含至少一个记录的c.idr.status <> 0

注意:如果r.status <> '0'字段属于字符类型,请使用r.status

答案 1 :(得分:1)

添加HAVING子句。

select c.id,count(*),
       group_concat(distinct(r.status not in ('Done','None'))) as mystatus
from cases c inner join reports r 
on (c.id = r.parent_id and r.parent_type = 'Cases' and r.deleted = 0)
where c.deleted = 0 
and c. status <> 'Late'
group by c.id
having mystatus = '0'