0

我可以为以下条件编写查询吗?

if (online_member == 0) {
    offline_member = offline_member + 1;
} else {
   online_member = online_member + 1;
}

我的查询:

SELECT `name`, 
        SUM(IF(online_member =0, 1, 0)) AS offline_member, 
        SUM(IF(online_member =1, 1, 0)) AS online_member 
FROM members

有没有更好的方法来编写上述查询?

4

1 回答 1

0

您可以将 MySQL 语法简化为:

SELECT `name`, 
        SUM(online_member = 0) AS offline_member, 
        SUM(online_member = 1) AS online_member 
FROM members
GROUP BY name;

我添加了 ,group by name因为如果您包含nameselect. 如果您只想要在线和离线成员的数量,总体而言,使用 ANSI 语法:

SELECT sum(case when online_member = 0 then 1 else 0 end) as offline_member,
       sum(case when online_member = 1 then 1 else 0 end) as online_member
FROM members;

老实说,这if是 MySQL 特有的语法。所以我的第一个版本是“更好”的,因为它更简洁。第二个版本在它是标准的意义上是“更好的”。但是,我还要强调if在 MySQL 中使用并没有错。

于 2013-09-20T02:52:43.827 回答