sql - mySQL 如何处理 ORDER BY 中的动态值

标签 sql mysql sql-order-by

它是我在阅读另一个 post 中的查询时偶然发现的.

以下面的查询为例(忽略排序的非实际使用):

SELECT 
*
FROM Members 
ORDER BY (TIMESTAMPDIFF(FRAC_SECOND, DateCreated , SYSDATE()))

假设“Members”表的行数很大(或者查询足够复杂,至少需要十几毫秒才能执行)。 mySQL或其他主流数据库引擎如何评估“ORDER BY”中的“SYSDATE()”?

假设查询需要半秒,“SYSDATE”的微秒 (FRAC_SECOND) 更改 1000 X 1000 X 0.5 = 500 000 次。

我的问题是:

  1. “SYSDATE”是否固定在 查询执行的开始或它 得到评估和变化作为 执行进度?
  2. 如果是后者,我可以假设顺序可能会困惑吗?

更新:
我的原始帖子使用 NOW 作为动态值的示例,现在是 SYSDATE

最佳答案

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 as of MySQL 5.0.12.

http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_now

换句话说,它只在执行语句时执行一次。 然而,如果你想获得每次执行的时间,你应该使用 SYSDATE

As of MySQL 5.0.12, SYSDATE() returns the time at which it executes. This differs from the behavior for NOW(), which 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.)

http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_sysdate

更新:
好吧,据我所知,Order by 将被执行,或者更好的说法是“只使用”一次。由于每次执行 SELECT 语句时 TIMESTAMPDIFF(FRAC_SECOND, DateCreated , SYSDATE()) 的值都会不同。因此,我认为(我再次认为)ORDER BY 将考虑 timestampdiff 的第一个评估值或最后一个评估值。无论如何,我认为通过执行这个 - 你每次都会得到一个随机订单。也许这里有比我更好的专家可以回答得更好。

关于sql - mySQL 如何处理 ORDER BY 中的动态值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1777389/

相关文章:

MySQL拒绝使用索引进行简单查询

sql - Oracle-选择字段具有小写字符的位置

mysql - 当只有一场比赛就足够时,如何显示整个小组

php - 在 SQL 和 PHP 中处理用户输入字符串的正确方法?

mysql - Yii - 文件验证规则在保存到数据库时将 JSON 数组设置为 NULL

angularjs - 如何使用angularJS为字符串数组而不是对象数组执行orderby

MySql Order by 未显示正确结果

mysql - 如何在 MySQL 上对 "intercalary"行进行排序

mysql - 如何将字段传递给 join 语句中的另一个 sql 短语

sql - 如何在 SQL Server 中使用 INNER JOIN 从多个表中删除