MySQL IF / Else语句作为列结果

时间:2013-09-20 02:34:06

标签: mysql sql

我可以针对以下情况编写查询吗?

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

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

1 个答案:

答案 0 :(得分: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,因为如果您在name中加入select,似乎就是这样。如果您只想要在线和离线成员的数量,总体而言,使用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特定的语法。所以我的第一个版本是“更好”的,因为它更简洁。第二个版本是“更好”的,因为它是标准的。但是,我还要强调在MySQL中使用if没有任何问题。