计算与MySQL中的每个条件匹配的行

时间:2009-10-18 05:31:55

标签: mysql grouping

请帮我看一下会改变以下数据的单个查询......

|id |status_a |status_b |
|+++++++++++++++++++++++|
|  1|active   |inactive |

...进入这一个。

|status_group      |count|
|++++++++++++++++++++++++|
|status_a.active   |    1|
|status_b.inactive |    1|

编辑:如果可以进行单次通过查询,那就更好了。此外,使用联合的查询是否只进行一次传递?

3 个答案:

答案 0 :(得分:3)

如果状态可以只是activeinactive,我建议采用不同的方法:

SELECT
    sum(if(status_a='active',1,0)) AS status_a_active,
    sum(if(status_a='inactive',1,0)) AS status_a_inactive,
    sum(if(status_b='active',1,0)) AS status_b_active,
    sum(if(status_b='inactive',1,0)) AS status_b_inactive
FROM table

否则你需要使用UNION方法,但我的方法有点不同。首先,您可以使用UNION ALL,因为您不需要删除结果中的重复项。我也只使用GROUP BY一次:

SELECT status_group, count(id)
FROM (
    SELECT CONCAT('status_a.', status_a) AS status_group, id FROM table
    UNION ALL
    SELECT CONCAT('status_b.', status_b) AS status_group, id FROM table
) a
GROUP BY status_group

答案 1 :(得分:2)

我有一个使用UNION的解决方案。如图所示:

SELECT 'status_a.active' AS status_group, COUNT(*) AS count FROM `test` WHERE status_a = 'active'
UNION
SELECT 'status_a.inactive' AS status_group, COUNT(*) AS count FROM `test` WHERE status_a = 'inactive'
UNION
SELECT 'status_b.active' AS status_group, COUNT(*) AS count FROM `test` WHERE status_b = 'active'
UNION
SELECT 'status_b.inactive' AS status_group, COUNT(*) AS count FROM `test` WHERE status_b = 'inactive'

基本上,它会查询status_a或status_b处于活动状态的每个条件。我们得到了四个这样的查询,我们将UNION应用于所有这些查询。

答案 2 :(得分:1)

我想,我不久前要发表评论,这也是一个比hw更短的解决方案。

SELECT CONCAT('status_a.', status_a) AS stat, COUNT(id) FROM base GROUP BY stat 
UNION
SELECT CONCAT('status_b.', status_b) AS stat, COUNT(id) FROM base GROUP BY stat