如何在一个查询中执行几种不同的计数聚合

时间:2019-03-28 08:04:06

标签: mysql

我正在执行查询,该查询必须选择count(*)输出并将插入结果插入另一个表,如下所示:

INSERT INTO db1.table1 (stopped) SELECT count(*) 
FROM db2.table2 WHERE condition=2;

但是,我需要此查询来根据不同条件对输出进行计数。如何将所有此类查询合并为一个查询

INSERT INTO db1.table1 (active) SELECT count(*) 
FROM db2.table2 WHERE condition=1;
INSERT INTO db1.table1 (susp) SELECT count(*) 
FROM db2.table2 WHERE condition=2 and option=4;

1 个答案:

答案 0 :(得分:0)

您可以尝试使用union all

SELECT count(*)  as cnt FROM db2.table2 WHERE condition=2
union all
SELECT count(*) FROM db2.table2 WHERE condition=1
union all 
SELECT count(*) FROM db2.table2 WHERE condition=2 and option=4