SQL条件取决于同一查询中的结果

时间:2017-06-09 09:10:28

标签: mysql sql

我有这个mySQL声明:

SELECT (SELECT COUNT(id) from online_users WHERE name='lol') as online, id, name, city
FROM players 
WHERE name='lol'
AND last_action < date_sub(now(), interval 1 hour)

然而我希望last_action间隔变化;如果online为1则为1分钟,如果online为0则为1小时

这可以在一个查询中完成吗?怎么样?

2 个答案:

答案 0 :(得分:0)

SELECT (SELECT COUNT(id) from online_users WHERE name='lol') as online, id, name, city
FROM players 
WHERE name='lol'
AND last_action < date_sub(now(), interval 1 CASE WHEN online=0 THEN hour ELSE MINUTE END)

尝试以上代码。

希望这会有所帮助。

答案 1 :(得分:0)

您可以使用OR条件,如下所示:

SELECT (SELECT COUNT(id) from online_users WHERE name='lol') as online, id, name, city
FROM players 
WHERE name='lol'
AND ((last_action < date_sub(now(), interval 1 hour) AND online = 1) OR (last_action < date_sub(now(), interval 1 minute) AND online = 0))