在MySQL中将字符串与“大于”和“小于”比较是安全的吗? [英] Is it safe to compare strings with 'greater than' and 'less than' in MySQL?
问题描述
MySQL(5.1.41-3ubuntu12.10-log)似乎可以使用>(大于)和< (小于):
MySQL (5.1.41-3ubuntu12.10-log) seems to give predictable results on string comparison using > (greater than) and < (less than):
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 |
+----+-------------+----------+-------+-----------------+------+---------+------+------+--------------------------+
这不会
推荐答案
我认为有一些问题,你可以有关详细信息,请查看文档:
I think there are some gotchas, you can have a look at documentation here for some details :
http://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html
如果你的字段也有空值,你还应该看看一个null安全的比较运算符:
http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_equal-to
If your fields have null values too, you should also take a look at null-safe comparision operator: 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中将字符串与“大于”和“小于”比较是安全的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!