问题
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