MySQL5.6中date和string的转换和比较

Conversion & Comparison, involving strings and dates in MySQL 5.6

我们有张表,表中有一个字段dpt_date,SQL类型为date type,表示离开日期。
我们将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'。
It can be inferred that conversion from string to date and comparison between dates is not as efficient as conversion from date to string and string comparison.
 
可以查看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.
 
 
 
 
 
上一篇:opencv实战——PCA算法的应用


下一篇:Maven*存储库