Mysql INTERVAL SQL语句问题
我在MySQL终端里用以下的SQL语句,运行得很好。
select * from metric_measured_value where metric_id=18 and measurement_time>(now()-INTERVAL 2 year);
但是,当我在Python代码里用这个语句时,它就不行了。
res = self._db.Query("""SELECT * FROM metric_measured_value
WHERE metric_id = %s
AND measurement_time>(now()-%s)""",
(metric_id, max_interval))
这里的metric_id是18,max_interval是“INTERVAL 2 year”。
错误信息是:截断了不正确的DOUBLE值:'INTERVAL 2 year'。
我哪里出错了呢?
谢谢你的帮助。
2 个回答
2
与其在数据库中计算时间间隔,为什么不在Python中计算,然后把结果传入你的测量时间呢?
from datetime import date
max_interval = 2
today = date.today()
interval = date.today()
interval = interval.replace(year=interval.year - max_interval)
delta = today - interval
res = self._db.Query("""SELECT * FROM metric_measured_value
WHERE metric_id = %s
AND measurement_time > %s""",
(metric_id, delta.days))
刚刚在关于Gmail风格日期格式化的问题中看到这个建议,提到了一个相对日期模块。这个模块是相对于现在的时间来说的,可能会给你一些灵感。
2
这可能是因为你的数据库访问库使用了预处理语句。INTERVAL
是 MySQL 的一个关键字,通常不应该作为参数传递给预处理语句。