mysql cast as interval

2019-08-06 23:15发布

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条回答
手持菜刀,她持情操
2楼-- · 2019-08-06 23:58

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.

查看更多
登录 后发表回答