MySQL:MySQL層比較函式呼叫

gaopengtttt發表於2020-08-06

一、問題來源

最近遇到一個日期比較的問題如下:

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

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/7728585/viewspace-2709839/,如需轉載,請註明出處,否則將追究法律責任。

相關文章