mysql cast as interval

匆匆过客 提交于 2020-01-15 11:50:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!