我可以在一个查询中选择更多计数吗?

时间:2011-04-25 19:09:10

标签: php sql

我的表格中有一个名为type的字段,其中可能有3行:123

现在,我根本不关心3。我需要计算type = 1type = 2的行数。我这样做有2个查询,如下:

查询1:SELECT COUNT(id) as count FROM users WHERE type='1'
问题2:SELECT COUNT(id) as count FROM users WHERE type='2'

我只能使用一个查询执行此操作吗?如果是的话,我应该,不是吗?查询将如何显示?

4 个答案:

答案 0 :(得分:10)

SELECT type,
       COUNT(id) AS count
  FROM users
 WHERE type IN ('1','2')
 GROUP BY type

答案 1 :(得分:3)

SELECT type, COUNT(id) AS count
FROM users
GROUP BY type
HAVING type < 3

答案 2 :(得分:-2)

SELECT sum(case when type = '1' then 1 else 0 end) as count_for_one,
       sum(case when type = '2' then 1 else 0 end) as count_for_tow
FROM users
WHERE type IN ('1','2')

答案 3 :(得分:-2)

如果你想要单独的数字,

SELECT SUM(IF(type='1', 1, 0)), SUM(IF(type='2', 1, 0)) 
FROM users WHERE type IN ('1', '2')