【问题标题】:MySQL apply multiple conditions in one query [duplicate]MySQL在一个查询中应用多个条件[重复]
【发布时间】:2015-02-20 08:56:52
【问题描述】:

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

id
login
status

现在我想用PHP创建一个统计页面,我想看看有多少用户状态=0,有多少用户状态=1,有多少用户状态=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

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

【问题讨论】:

    标签: php mysql sql


    【解决方案1】:

    你可以按状态分组,这样总结不同的状态。

    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
    

    【讨论】:

    • 这很快,而且有效!谢谢
    • Query1 时间 = 0.0395s 在有 50k 用户的表上; Query2 时间 = 0.0250 秒对 50k 用户的表进行第二次查询
    • 这些查询为每个状态返回 2 个不必要的列
    • 当 status = '0' 他们将返回 row '0', some_count, 0, 0;当 status = '1' 他们将返回 row '1', 0, some_count, 0
    【解决方案2】:

    查询返回 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'
    

    【讨论】:

    • 在有 50k 用户的表上查询时间 = 0.0240 秒。使用 WHERE 而不是 GROUP BY 时似乎更有效
    • 顺便说一句,您的查询中有错误...将第二个“when”替换为“then”
    猜你喜欢
    • 2014-06-01
    • 2013-10-03
    • 2014-10-22
    • 2018-03-09
    • 2021-11-05
    • 2012-06-21
    • 2010-11-21
    • 2021-08-07
    • 2014-11-15
    相关资源
    最近更新 更多