2016-02-18 36 views
0

如何选择mystatus场只包含0选择记录中GROUP_CONCAT()包含一个char

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

回答

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' 
+0

这对我很有用:D非常感谢。 – May

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的子句的谓词使用条件聚合用于过滤掉含至少一个记录与r.status <> 0c.id基团。

注意:使用r.status <> '0'在案件r.status字段是字符类型。

+0

因为我的状态是一个字符串列,你不需要撇号吗? – sagi

+0

@sagi请参阅我在评论前添加的注释! –

+1

确实你没有:) +1 – sagi