简单表
________________________________________________
| id | parent_id | name | some_condition_field |
------------------------------------------------
我想要行集:
________________________________________________________________________________
| id | name | count_childs_with_condition_one | count_childs_with_condition_two |
---------------------------------------------------------------------------------
有可能吗?变量,UNION等.. ???
答案 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