【坑】 MySQL中,字符串和數值的比較
官方文檔:https://dev.mysql.com/doc/refman/5.7/en/comparison-operators.html
原文:
Comparison operations result in a value of 1 (TRUE), 0 (FALSE), or NULL. These operations work for both numbers and strings. Strings are automatically converted to numbers and numbers to strings as necessary.
也就是說在比較的時候,String是可能會被轉為數字的。
對於數據開頭的字符串,轉成數字後會自動丟棄後面的字母部分,只留下純數字進行比較。
對於沒有數字的那些字符串,與數值進行比較的時候,就只剩下0去和其他數值進行比較了。
例子:
1、對於沒有數字的那些字符串,與數值進行比較的時候,就只剩下0去和其他數值進行比較了。:
root [(none)] >select 0=‘abc‘;
+---------+
| 0=‘abc‘ |
+---------+
| 1 |
+---------+
1 row in set, 1 warning (0.00 sec)
root [(none)] >show warnings;
+---------+------+-----------------------------------------+
| Level | Code | Message |
+---------+------+-----------------------------------------+
| Warning | 1292 | Truncated incorrect DOUBLE value: ‘abc‘ |
+---------+------+-----------------------------------------+
1 row in set (0.00 sec)
2、對於數據開頭的字符串,轉成數字後會自動丟棄後面的字母部分,只留下純數字進行比較。
root [(none)] >select 11=‘010abc‘;
+-------------+
| 11=‘010abc‘ |
+-------------+
| 0 |
+-------------+
1 row in set, 1 warning (0.00 sec)
root [(none)] >show warnings;
+---------+------+--------------------------------------------+
| Level | Code | Message |
+---------+------+--------------------------------------------+
| Warning | 1292 | Truncated incorrect DOUBLE value: ‘010abc‘ |
+---------+------+--------------------------------------------+
1 row in set (0.00 sec)
官方網站給的例子更多,更多感興趣的可以去看看。
其實字符串和數值比較最大的坑在於:它會導致查詢不能用到索引,直接就影響了查詢的效率。
【坑】 MySQL中,字符串和數值的比較