我有类似的查询:
-- MySQL Query
SELECT * FROM table1 WHERE start_date >= CURRENT_TIMESTAMP - INTERVAL 7 DAY
-- MSSQL Query
SELECT * FROM table1 WHERE start_date >= GETDATE() - 7
由于右侧的表达式不依赖于列值,我是否应该期望查询优化器将其优化为常量值,例如:
SELECT * FROM table1 WHERE start_date >= '2012-04-28 14:54:31'
或者我应该计算常量并使用代码构建查询。
最佳答案
根据 MySQL 的文档 NOW()
函数(CURRENT_TIMESTAMP
是同义词):
NOW()
returns a constant time that indicates the time at which the statement began to execute. (Within a stored function or trigger,NOW()
returns the time at which the function or triggering statement began to execute.) This differs from the behavior forSYSDATE()
, which returns the exact time at which it executes.
因此,查询优化器会根据需要将其视为常量。一 jar see this在 EXPLAIN
输出中。
我不能代表 MSSQL,尽管也许 this blog值得一读吗?
关于mysql - 当表达式不涉及列时,查询优化器是否将表达式转换为常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10460812/