mysql - 当表达式不涉及列时,查询优化器是否将表达式转换为常量

标签 mysql sql sql-server

我有类似的查询:

-- 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 for SYSDATE(), which returns the exact time at which it executes.

因此,查询优化器会根据需要将其视为常量。一 jar see thisEXPLAIN 输出中。

我不能代表 MSSQL,尽管也许 this blog值得一读吗?

关于mysql - 当表达式不涉及列时,查询优化器是否将表达式转换为常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10460812/

相关文章:

php - JOIN 3 个表中的行 WHERE table.column1 = tableS.column1 = tableT.column1

sql - 仅删除前导或尾随回车符

sql-server - 具有多个表和键的 INNER JOIN

mysql - 跟进查询,不包括已收集的结果

mysql - 删除在单独表中找不到 userID 的行

java - 如何在 Java 中为具有组合键的表编写删除 SQL 语句?

sql - DATE 的 Oracle SQL 比较返回错误结果

sql - 在 Netezza 中使用科学计数法

sql-server - 在 Azure Databricks 中使用 Python 将 DF 写入 SQL Server

c# - 调用存储过程时使用 Entity Framework 处理响应时出错