数据库
首页 > 数据库> > 在MySQL中比较“大于”和“小于”的字符串是否安全?

在MySQL中比较“大于”和“小于”的字符串是否安全?

作者:互联网

MySQL(5.1.41-3ubuntu12.10-log)似乎使用>给出了字符串比较的可预测结果. (大于)和< (少于):

select "a" > "a", "a" > "b", "b" > "a", "ab" > "aa", "ab" > "aabbbb";
+-----------+-----------+-----------+-------------+-----------------+
| "a" > "a" | "a" > "b" | "b" > "a" | "ab" > "aa" | "ab" > "aabbbb" |
+-----------+-----------+-----------+-------------+-----------------+
|         0 |         0 |         1 |           1 |               1 | 
+-----------+-----------+-----------+-------------+-----------------+

而且似乎也使用了键:

explain select productcode from products where productcode < 'no'; 
+----+-------------+----------+-------+-----------------+------+---------+------+------+--------------------------+
| id | select_type | table    | type  | possible_keys   | key  | key_len | ref  | rows | Extra                    |
+----+-------------+----------+-------+-----------------+------+---------+------+------+--------------------------+
|  1 | SIMPLE      | products | range | productcode,ppp | ppp  | 34      | NULL |  432 | Using where; Using index |
+----+-------------+----------+-------+-----------------+------+---------+------+------+--------------------------+

这似乎没有记录 – 它是一个可靠的跨平台功能吗?

解决方法:

我认为有一些问题,您可以在这里查看文档以获取一些细节:

http://dev.mysql.com/doc/refman/5.5/en/comparison-operators.html

如果您的字段也具有空值,您还应该查看null-safe比较运算符:
http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_equal-to

例如:

mysql> select "a" > "a ", "A" > "a" , "aB"  > "ab" , "a" >= NULL , "a" <=> NULL ;
+------------+-----------+--------------+-------------+--------------+
| "a" > "a " | "A" > "a" | "aB"  > "ab" | "a" >= NULL | "a" <=> NULL |
+------------+-----------+--------------+-------------+--------------+
|          0 |         0 |            0 |        NULL |            0 |
+------------+-----------+--------------+-------------+--------------+

标签:mysql,comparison,string-comparison
来源: https://codeday.me/bug/20191001/1840556.html