MySQL 5.6 date 与 string 的转换和比较

我们有张表,表中有一个字段 dpt_date ,SQL 类型为 date,表示离开日期。
我们将 dpt_date 与字符串 ‘2016-03-09’ 进行比较,发现效率低于 dpt_date 转换为字符串再与 ‘2016-03-09’ 进行比较:
SELECT * FROM tbl_name WHERE dpt_date = '2016-03-09' 效率低于 SELECT * FROM tbl_name WHERE FORMAT_DATE(dpt_date, '%Y-%m-%d')='2016-03-09'。

字符串的比较比日期更高效。

 
可以查看 Type Conversion in Expression Evaluation 中的相关部分:
The following rules describe how conversion occurs for comparison operations:
  • If one or both arguments are NULL, the result of the comparison is NULL, except for the NULL-safe <=> equality comparison operator. For NULL <=> NULL, the result is true. No conversion is needed.
  • If both arguments in a comparison operation are strings, they are compared as strings.
  • If both arguments are integers, they are compared as integers.
  • Hexadecimal values are treated as binary strings if not compared to a number.
  • If one of the arguments is a TIMESTAMP or DATETIME column and the other argument is a constant, the constant is converted to a timestamp before the comparison is performed. This is done to be more ODBC-friendly. This is not done for the arguments to IN(). To be safe, always use complete datetime, date, or time strings when doing comparisons. For example, to achieve best results when using BETWEEN with date or time values, use CAST() to explicitly convert the values to the desired data type.
    A single-row subquery from a table or tables is not considered a constant. For example, if a subquery returns an integer to be compared to a DATETIME value, the comparison is done as two integers. The integer is not converted to a temporal value. To compare the operands as DATETIME values, use CAST() to explicitly convert the subquery value to DATETIME.
  • If one of the arguments is a decimal value, comparison depends on the other argument. The arguments are compared as decimal values if the other argument is a decimal or integer value, or as floating-point values if the other argument is a floating-point value.
  • In all other cases, the arguments are compared as floating-point (real) numbers.
 
 
 
 
 
原文地址:https://www.cnblogs.com/huangzejun/p/8143530.html