MySql: Compare 2 strings which are numbers?

折月煮酒 提交于 2019-12-30 17:33:25

问题


I have a column in my table, it holds values such as 100012345. The column is varchar. Now I want to compare this to similiar values in a where:

... where myColumn > '100012345'

for example. How could I do that?

Thanks!


回答1:


select * from your_table
where cast(your_column as signed) = 100012345



回答2:


Have you tried to do it normally, like this:

... where myColumn > 100012345

That should work!, mysql automatically casts a string to number when it's in the context of a number operation. In the same way it casts a number to string if it's used in a string context. See the examples in the type conversion docs:

To cast a string to a numeric value in numeric context, you normally do not have to do anything other than to use the string value as though it were a number:

mysql> SELECT 1+'1';
       -> 2

If you use a string in an arithmetic operation, it is converted to a floating-point number during expression evaluation.

If you use a number in string context, the number automatically is converted to a string:

mysql> SELECT CONCAT('hello you ',2);
        -> 'hello you 2'



回答3:


You don't have to cast strings into integers to compare, mysql does it automatically.

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




回答4:


You can cast the value to an integer:

CAST(myColumn AS INTEGER)



来源:https://stackoverflow.com/questions/12749219/mysql-compare-2-strings-which-are-numbers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!