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

Ken*_*Ken 7 mysql comparison string-comparison

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 | 
+-----------+-----------+-----------+-------------+-----------------+
Run Code Online (Sandbox Code Playgroud)

并且似乎也使用了键:

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 |
+----+-------------+----------+-------+-----------------+------+---------+------+------+--------------------------+
Run Code Online (Sandbox Code Playgroud)

似乎没有记录在案-它是可靠的跨平台功能吗?

Dhr*_*hak 5

我认为有一些问题,您可以查看此处的文档以了解一些详细信息:

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

如果您的字段也有空值,您还应该看看空安全比较运算符: 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 |
+------------+-----------+--------------+-------------+--------------+
Run Code Online (Sandbox Code Playgroud)

  • 第一个链接实际上没有任何有关比较此类字符串的信息。 (5认同)