4

A 有一个名为 key 的列 - 1,1,2,2,2,2,3 现在我用 3 个查询来做:

SELECT count(key) as k FROM `test` WHERE key=1
SELECT count(key) as k FROM `test` WHERE key=2
SELECT count(key) as k FROM `test` WHERE key=3

如何在一次查询中计算 1、2、3 的数量?

4

4 回答 4

9

使用分组:

SELECT `key`, COUNT(*) FROM `test` GROUP BY `key`;
于 2013-08-25T08:03:33.087 回答
1

你可以这样做

select count(key) as K FROM test where key in (1,2,3)
于 2013-08-25T07:56:06.440 回答
1

这是另一种选择:

SELECT sum(key=1) as k1, sum(key=2) as k2,sum(key=3) as k3 FROM `test`

如果键的值是其他组的一部分,您还可以按列添加组。

于 2017-05-26T13:52:20.543 回答
0

试试这个

SELECT  COUNT(Key) as K
        FROM 
        test 
        GROUP BY Key
于 2013-08-25T08:07:52.543 回答