问题
I'm looking for a way to select the row in which the current time is between two set values in the row. I've set up a table with 3 columns, 2 of them hold a timestamp (HH:MM:SS), the other one a string. Is there a way I can get the string corresponding to the current time? To put it in a more abstract way:
SELECT String FROM TableName WHERE (Current Time) BETWEEN (Lower Limit Time Value) AND (Upper Limit Time Value);

So basically, based on the current time, my script should output the correct string.
How do I go about this? Thanks!
回答1:
In MySQL
, timestamp is quite a confusing word.
If they are lowerlimit
and upperlimit
are TIME
columns from 00:00:00
to 23:59:59
:
SELECT String
FROM TableName
WHERE CURTIME() BETWEEN lowerlimit AND upperlimit
OR CURTIME() BETWEEN SUBTIME(upperlimit, '24:00:00') AND lowerlimit
OR SUBTIME(CURTIME(), '24:00:00') BETWEEN SUBTIME(upperlimit, '24:00:00') AND lowerlimit
This will handle midnight transitions correctly.
回答2:
SELECT string_col
FROM your_table
WHERE CURTIME() BETWEEN lower_limit_col AND upper_limit_col
回答3:
The way you did is pretty much it:
SELECT String FROM TableName WHERE CURTIME() BETWEEN (Lower Limit Time Value) AND (Upper Limit Time Value);
回答4:
the type of the two columns should be time (and not timestamp). Then, the answer is in your question :
select string from tablename where curtime() between lowerlimit and upperlimit
Just make sure that the night doesnt go from 22:00:00 to 06:00:00 though, or it won't work. But you might introduce two intervals for the might : one from 22:00:00 to 24:00:00, and another one from 00:00:00 to 06:00:00.
来源:https://stackoverflow.com/questions/4758095/mysql-select-where-time-now-between-tablevalue-and-tablevalue