简体   繁体   中英

SQL condition depending on result in same query

I have this mySQL statement:

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)

however I want the last_action interval to vary; 1 minute if online is 1, and 1 hour if online is 0

Can this be done all in one query? How so?

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)

Try above code.

Hope this will help.

You could use an OR condition, like this:

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM