MySQL:MySQL层比较函数调用


一、问题来源

最近遇到一个日期比较的问题如下:

root@localhost:test:10:25:48>select from_unixtime(1596680255);
+---------------------------+
| from_unixtime(1596680255) |
+---------------------------+
| 2020-08-06 10:17:35       |
+---------------------------+
1 row in set (0.00 sec)
root@localhost:test:10:25:52>select from_unixtime(1596680255,'%Y-%m-%d') < '2020-08-1';
+----------------------------------------------------+
| from_unixtime(1596680255,'%Y-%m-%d') < '2020-08-1' |
+----------------------------------------------------+
|                                                  1 |
+----------------------------------------------------+
1 row in set (2.70 sec)
root@localhost:test:10:25:59>select from_unixtime(1596680255) < '2020-08-1';
+-----------------------------------------+
| from_unixtime(1596680255) < '2020-08-1' |
+-----------------------------------------+
|                                       0 |
+-----------------------------------------+
1 row in set (2.36 sec)

按理来说from_unixtime(1596680255,’%Y-%m-%d’) < ‘2020-08-1’ 应该是false才对,但是返回为true,因此怀疑为字符串比较的方式

二、问题验证

首先关闭gtid通过create table as 来验证一下字段类型如下:

create table testit951
as
select from_unixtime(1596678161,'%Y-%m-%d') as "tt"
create table testit952
as
select from_unixtime(1596678161) as "tt"

通过这种方式发现两种建表字段为varchar和datetime类型。通过源码验证可以看到如下:

Breakpoint 5, Arg_comparator::compare_string (this=0x7fffe40167c0) at /cdh/mysqldebug/percona-server-5.7.29-32/sql/item_cmpfunc.cc:1672
1672      if ((res1= (*a)->val_str(&value1)))
(gdb) c
Continuing.
Breakpoint 4, Arg_comparator::compare_datetime (this=0x7fffe40164c8) at /cdh/mysqldebug/percona-server-5.7.29-32/sql/item_cmpfunc.cc:1509
1509      THD *thd= current_thd;
(gdb) c
Continuing.

可以看到内部通过了string和datetime两种类型来比较。因此得到证明。最后留下比较函数的位置:
Item_cmpfunc.cc
image.png

请使用浏览器的分享功能分享到微信等