MySQL - 根据一个查询中的状态计算活动/非活动/禁用用户并选择用户

时间:2017-05-02 14:28:40

标签: mysql

我有用户表,用户可以拥有以下三种状态之一:

active (0)
inactive (1)
banned (2)

是否可以单独计算所有类型的用户,并且只允许用户在一个查询中选择状态。例如,我想显示有多少用户处于活动/非活动/禁用状态并显示所有活动用户?

表结构很简单:

id | firstName | lastName | email | password | status

I am trying to achieve something like this:

Active Users (10) | Inactive Users (2) | Banned Users (7)

List of all active users:

1) John Doe
2) John Doe
3) John Doe...

2 个答案:

答案 0 :(得分:4)

单一查询无法获得预期的输出!

您可以使用

获取status概述
SELECT 
    SUM(CASE WHEN status = 0 THEN 1 ELSE 0 END) AS active_users,
    SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) AS inactive_users,
    SUM(CASE WHEN status = 2 THEN 1 ELSE 0 END) AS banned_users
FROM users

status = 0(有效)的所有用户都可以使用以下

SELECT * FROM users
WHERE status = 0

答案 1 :(得分:0)

Sebastian Brosch 答案的简短版本:

SELECT 
    SUM(status = 0) AS active_users, 
    SUM(status = 1) AS inactive_users, 
    SUM(status = 2) AS banned_users 
FROM users;