Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
520 views
in Technique[技术] by (71.8m points)

comparison - Is it safe to compare strings with 'greater than' and 'less than' in MySQL?

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

and also seems to make use of keys:

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

This doesn't seem to be documented - is it a dependable cross-platform feature?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think there are some gotchas, you can have a look at documentation here for some details :

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

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

example :

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...