0

简单表

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

我想要行集:

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

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

4

1 回答 1

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
于 2012-07-15T15:05:24.733 回答