سؤال

I KNOW THAT ITS STUPID IDEA TO COMPARE NUMBER WITH VARCHAR FIELD AND I SHOULDN'T COMPARE IT, BUT I JUST WANT TO UNDERSTAND THE REASON.

I am having table with following schema.

Table: user
--------------------
number varchar(24)

I am having MyISAM as storage engine.

The number field is containing mixed data i.e. numbers(like '9999999') and strings(like 'signup').

I am trying to run following query.

SELECT * FROM user where number=0

But its returning all the rows where number field is containing either string value like 'signup' or empty in number field.

While if I run following queries..

SELECT * FROM user where number=1 or SELECT * FROM user where number=97654

They are not returning any rows as none of the row is having 1 or 97654 value in its number field.

Can someone help me to understand how mysql is comparing 0 with varchar field ?

هل كانت مفيدة؟

المحلول

signup and other empty values are returned because MySQL implicitly converts the strings into integers. when the string is invalid or cannot be converted into int, the value is 0 that's why it's returning.

نصائح أخرى

It returns all entries where number is not convertible to a number, or is the string "0". This is because the comparison converts the varchar to an int beforehand, which results in the value 0.

It is clearly described in the manual

For actual comparison you can use below query

SELECT * FROM user where CAST(`number` AS SIGNED) = 1
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top