mysql where exact match

后端 未结 4 732
梦谈多话
梦谈多话 2021-01-14 04:47

When i write this query

SELECT cd.title, cd.city FROM coupon_detail cd WHERE cd.id = 260;

return

title            city  
--         


        
4条回答
  •  一整个雨季
    2021-01-14 05:11

    Well, you should not use quote if the id is INT. The way MySQL does is if you use String to compare a INT, it uses just the valid initial integer from start.

    see this:

    mysql> desc coupon_detail;
    +-------+--------------+------+-----+---------+-------+
    | Field | Type         | Null | Key | Default | Extra |
    +-------+--------------+------+-----+---------+-------+
    | id    | int(11)      | YES  |     | NULL    |       |
    | title | varchar(100) | YES  |     | NULL    |       |
    | city  | varchar(100) | YES  |     | NULL    |       |
    +-------+--------------+------+-----+---------+-------+
    3 rows in set (0.04 sec)
    
    mysql> SELECT cd.title, cd.city FROM coupon_detail cd WHERE cd.id = 'ff260';
    Empty set, 1 warning (0.00 sec)
    
    mysql> SELECT cd.title, cd.city FROM coupon_detail cd WHERE cd.id = '260ff';
    +-----------------+--------+
    | title           | city   |
    +-----------------+--------+
    | Butterfly world | Mohali |
    +-----------------+--------+
    1 row in set, 1 warning (0.00 sec)
    
    mysql> SELECT cd.title, cd.city FROM coupon_detail cd WHERE cd.id = 260;
    +-----------------+--------+
    | title           | city   |
    +-----------------+--------+
    | Butterfly world | Mohali |
    +-----------------+--------+
    1 row in set (0.00 sec)
    
    mysql> SELECT cd.title, cd.city FROM coupon_detail cd WHERE cd.id = 26011;
    Empty set (0.00 sec)
    

    The idea is not to mix numbers and aphabets to compare a INT column. If you have to you may consider

    • converting ID column to VARCHAR. In that case auto-increment may go away.
    • have application logic to query only the strings that has numerics.

提交回复
热议问题