首頁  >  問答  >  主體

mysql - 使用 where id=201511051505538905 对于 char 类型字段查询的坑?

char 类型存储大数字时,如果查询 sql 直接用 id=201511051505538905 这种不标准的方式查询时,会因为具体 id 值的不同,出现查询不到的情况。 正确做法是加上单引号',便能正确查询到

请问背后的实质原因是什么?

阿神阿神2742 天前627

全部回覆(3)我來回復

  • ringa_lee

    ringa_lee2017-04-17 13:29:55

    感謝 @鋒雲戰錦 和 @蘇生不惑 的回答, 我從 mysql 官網摘抄瞭如下解釋,能很好的解答我的疑惑:

    Comparisons that use floating-point numbers (or values that are converted to floating-point numbers) are approximate because such numbers are inexact. This might lead to results 網站給出 results 的例子如下:

    mysql> SELECT '18015376320243458' = 18015376320243458;
            -> 1
    mysql> SELECT '18015376320243459' = 18015376320243459;
            -> 0
    https://dev.mysql.com/doc/refman/5.7/en/type-conversion.html

    回覆
    0
  • PHPz

    PHPz2017-04-17 13:29:55

    id=201511051505538905
    它的資料型別為int
    而你的id的資料型別是string,當然查不到,但你可以轉換成int
    cast(id as int)

    回覆
    0
  • 迷茫

    迷茫2017-04-17 13:29:55

    where id=201511051505538905 id是char型別 而你用數字比較,mysql會將字串轉為數字,就是0 201511051505538905 != 0

    回覆
    0
  • 取消回覆