问题
is it possible to cast as an interval in MySQL?
I want to evaluate a value from the query as an interval, like this:
select DATE_SUB(NOW(),CAST(user.expiry_interval AS interval))
where user.expiry_interval is 'INTERVAL 1 WEEK' or something like that
select DATE_SUB(NOW(),CAST('INTERVAL 1 week' AS INTERVAL))
回答1:
INTERVAL is not a data type, but a keyword that converts a human-readable "duration" string into an integer. As such, "casting to INTERVAL
" makes no sense.
If your "interval" input is variable, then this can work but you can't take the entire thing from a string any more than you can "cast" the string "SELECT * FROM tbl"
into a query expression. You can use a variable for the numeric operand (see below) but I think that's it.
SELECT DATE_SUB(NOW(), INTERVAL `x` DAY) FROM `tbl`;
You'll have to resort to CASE
if you want logic that's stronger than that. Or... store integer durations in the first place.
来源:https://stackoverflow.com/questions/7512744/mysql-cast-as-interval