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

时间:2011-11-10 17:32:57

标签: 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 | 
+-----------+-----------+-----------+-------------+-----------------+

并且似乎也使用了键:

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 |
+----+-------------+----------+-------+-----------------+------+---------+------+------+--------------------------+

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

2 个答案:

答案 0 :(得分:2)

我认为有一些问题,你可以在这里查看文档了解一些细节:

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

如果你的字段也有空值,你还应该看看null-safe comparision运算符: 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 |
+------------+-----------+--------------+-------------+--------------+

答案 1 :(得分:1)

这些比较很常见。我确信通过ascii值或其他一些编码来比较字符串是跨平台支持的。对不起,我没有任何资源支持它。这可能是它在内部比较字符串(用于排序等)的方式。我希望这是一个主要特征。