Mysql treating varchar as int bug?

折月煮酒 提交于 2019-12-12 00:33:23

问题


I just ran this query:

UPDATE mytable SET mycol='text' WHERE mycol=0;

The point being that the column mycol is a varchar, yet i treated is as an int as well. To my surprise, the where clause evaluated to true on ALL rows of the table, empty or not.

So, why does a nonempty string compare equal to an integer zero?


回答1:


This is very well documented behavior in MySQL.

When a string is encountered in a context that calls for a number, MySQL converts the string to a number, starting with digits at the beginning of the string. It stops when there are no digits. So, a string with no digits becomes 0.

If you want a proper comparison, use single quotes:

UPDATE mytable SET mycol='text' WHERE mycol = '0';

Here is the exact quote:

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



来源:https://stackoverflow.com/questions/17843329/mysql-treating-varchar-as-int-bug

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