MySQL在一个查询中应用多个条件

时间:2015-02-20 08:56:53

标签: php mysql sql

我有一个名为users的表,其中包含以下列:

id
login
status

现在我想在PHP中创建一个统计页面,我想看看有多少用户有status = 0,有多少用户有status = 1,有多少用户有status = 2.

我希望以最有效的方式执行此操作,而无需运行3个查询。

现在我只知道用UNION中的3个查询执行此操作:

(SELECT COUNT(*) FROM users WHERE status='0') UNION (SELECT COUNT(*) FROM users WHERE status='1') UNION (SELECT COUNT(*) FROM users WHERE status='2')

我不太了解SQL编程,但我认为这样的事情可能有用:

SELECT IF(status='0',stat0++),IF(status='1',stat1++),IF(status='2',stat2++) FROM users GROUP BY status

但它不起作用,因为语法错误

2 个答案:

答案 0 :(得分:3)

您可以按状态分组并总结不同的状态。

select status, 
       sum(status = 1) as status1_count,
       sum(status = 2) as status2_count,
       sum(status = 3) as status3_count
from users
group by status

这是MySQL语法。一般SQL ANSI语法将是

select status, 
       sum(case when status = 1 then 1 end) as status1_count,
       sum(case when status = 2 then 1 end) as status2_count,
       sum(case when status = 3 then 1 end) as status3_count
from users
group by status

答案 1 :(得分:1)

查询返回1行中的状态计数

select
  sum(case when status = '0' then 1 else 0 end) as c1,
  sum(case when status = '1' then 1 else 0 end) as c2,
  sum(case when status = '2' then 1 else 0 end) as c3
from users 
where status = '0' or status = '1' or status = '2'