MySQL层比较函数的调用方式

发布时间:2021-09-14 18:07 来源:亿速云 阅读:0 作者:chen 栏目: Mysql 欢迎投稿:712375056

这篇文章主要介绍“层比较函数的调用方式”,在日常操作中,相信很多人在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

免责声明:本站发布的内容(图片、视频和文字)以原创、来自本网站内容采集于网络互联网转载等其它媒体和分享为主,内容观点不代表本网站立场,如侵犯了原作者的版权,请告知一经查实,将立刻删除涉嫌侵权内容,联系我们QQ:712375056,同时欢迎投稿传递力量。