美文网首页
mysql 语句中数字与字符串比较的情况

mysql 语句中数字与字符串比较的情况

作者: 左希 | 来源:发表于2018-09-16 16:33 被阅读0次
    数据库

    一、 问题原因
    同事项目出现Bug,让我看看,项目在运行过程中一直出现同一条数据,而将sql在数据库执行是正常的,没有查到任何数据,但项目执行始终有一条数据,那这条数据怎么产生的呢?

    二、排查问题
    先排查是否链接数据库不对,排查正常,在排查是否存在缓存,排查没有,然后排查sql语句,sql排查了许久发现,传入给sql语句条件的占位符参数是""132456""这样的,而条件比较字段类型是int类型,最终查询出字段为0的数据

    三、为什么会这样呢?
    测试如下:

    mysql> select 'sss' = 0;
    +-----------+
    | 'sss' = 0 |
    +-----------+
    |         1 |
    +-----------+
    1 row in set
    
    
    mysql> select '0sss' = 0;
    +------------+
    | '0sss' = 0 |
    +------------+
    |          1 |
    +------------+
    1 row in set
    
    
    mysql> select '01sss' = 0;
    +-------------+
    | '01sss' = 0 |
    +-------------+
    |           0 |
    +-------------+
    1 row in set
    
    
    mysql> select '013sss' = 13
    ;
    +---------------+
    | '013sss' = 13 |
    +---------------+
    |             1 |
    +---------------+
    1 row in set
    
    mysql> select '113sss' = 13;
    +---------------+
    | '113sss' = 13 |
    +---------------+
    |             0 |
    +---------------+
    1 row in set
    
    

    查询通过查看MySQL给出的警告,都可以看到类似如下的信息

    mysql> show warnings;
    +---------+------+--------------------------------------------+
    | Level   | Code | Message                                    |
    +---------+------+--------------------------------------------+
    | Warning | 1292 | Truncated incorrect DOUBLE value: '113sss' |
    +---------+------+--------------------------------------------+
    1 row in set
    

    官方文档中关于比较的章节,其中说明Comparison operations result in a value of 1 (TRUE), 0 (FALSE), or NULL. These operations work for both numbers and strings. Strings are automatically converted to numbers and numbers to strings as necessary.。也就是说字符串根据需要自动转换为字符串和数字。

    
    mysql> select cast('123ab
    c' as signed);
    +--------------------------+
    | cast('123abc' as signed) |
    +--------------------------+
    |                      123 |
    +--------------------------+
    1 row in set
    
    mysql> select cast('1h
    23abc' as signed);
    +---------------------------+
    | cast('1h23abc' as signed) |
    +---------------------------+
    |                         1 |
    +---------------------------+
    1 row in set
    
    mysql> select cast('
    abc' as signed);
    +-----------------------+
    | cast('abc' as signed) |
    +-----------------------+
    |                     0 |
    +------------
    

    由此可见转换类型时,从左往右开始截取,如果有则截取出来,遇到不能转换的就终止,如果从开头就没有截取到匹配类型结果自然就是0。
    Comparison operations result in a value of 1 (TRUE), 0 (FALSE), or NULL.

    相关文章

      网友评论

          本文标题:mysql 语句中数字与字符串比较的情况

          本文链接:https://www.haomeiwen.com/subject/rphfnftx.html