在一个rowset mysql中选择两个计数条件

时间:2012-07-15 15:01:42

标签: mysql sql

简单表

________________________________________________
| id | parent_id | name | some_condition_field |
------------------------------------------------

我想要行集:

________________________________________________________________________________
| id | name | count_childs_with_condition_one | count_childs_with_condition_two |
---------------------------------------------------------------------------------

有可能吗?变量,UNION等.. ???

1 个答案:

答案 0 :(得分:2)

这是一个跨平台的解决方案:

对于单亲:

select count(case when some_condition_field = 'xxx' then 1 end) as CountXXX, 
    count(case when some_condition_field = 'yyy' then 1 end) as CountYYY
from MyTable
where parent_id = 123

对于所有父母:

select parent_id, 
    count(case when some_condition_field = 'xxx' then 1 end) as CountXXX, 
    count(case when some_condition_field = 'yyy' then 1 end) as CountYYY
from MyTable
group by parent_id

对于MySQL,您也可以使用以下语法:

select parent_id, 
    count(if(some_condition_field = 'xxx', 1, null) as CountXXX, 
    count(if(some_condition_field = 'yyy', 1, null)) as CountYYY
from MyTable
group by parent_id