我可以针对以下情况编写查询吗?
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
有没有更好的方法来编写上述查询?
答案 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
没有任何问题。