2016-02-18 37 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