mysql: why comparing a 'string' to 0 gives true?

前端 未结 3 951
灰色年华
灰色年华 2020-12-01 13:09

I was doing some MySQL test queries, and realized that comparing a string column with 0 (as a number) gives TRUE!

select \'string\'         


        
相关标签:
3条回答
  • 2020-12-01 13:25

    "Strings are automatically converted to numbers and numbers to strings as necessary." This means that in order to compare a string to a number, it tries to parse a number from the start of the string. In this case there is no number there, so it converts to 0, and 0 = 0 is true.

    0 讨论(0)
  • 2020-12-01 13:33

    if you want to fix it you can compare two strings:

    select 'string' = convert(0,char) as res --- res = 0
    
    0 讨论(0)
  • 2020-12-01 13:41

    MySQL automatically casts a string to a number:

    SELECT '1string' = 0 AS res; -- res = 0 (false)
    SELECT '1string' = 1 AS res; -- res = 1 (true)
    SELECT '0string' = 0 AS res; -- res = 1 (true)
    

    and a string that does not begin with a number is evaluated as 0:

    SELECT 'string' = 0 AS res;  -- res = 1 (true)
    

    Of course, when we try to compare a string with another string there's no conversion:

    SELECT '0string' = 'string' AS res; -- res = 0 (false)
    

    but we can force a conversion using, for example, a + operator:

    SELECT '0string' + 0 = 'string' AS res; -- res = 1 (true)
    

    last query returns TRUE because we ar summing a string '0string' with a number 0, so the string has to be converted to a number, it becomes SELECT 0 + 0 = 'string' and then again the string 'string' is converted to a number before being compared to 0, and it then becomes SELECT 0 = 0 which is TRUE.

    This will also work:

    SELECT '1abc' + '2ef' AS total; -- total = 1+2 = 3
    

    and will return the sum of the strings converted to numbers (1 + 2 in this case).

    0 讨论(0)
提交回复
热议问题