Querying a string from int column?

前端 未结 4 1868
眼角桃花
眼角桃花 2020-12-20 17:55

I have a table:

CREATE TABLE `ids` (
    id int(11) not null auto_increment,
    PRIMARY KEY (id)
);

It contains some IDs: 111, 112, 113, 1

4条回答
  •  旧巷少年郎
    2020-12-20 18:21

    You are comparing a string, just put the number with no quotes:

    SELECT * FROM `ids` WHERE id = 112
    

    If you dont, it will convert the string '112abcdefg' to a number and say its 112

    The response you are seeing is because you are trying to compare an integer column to a string value. In that case, MySQL will type-cast the string literal value to an integer, and when it does that it starts from the left of the string and as soon as it reaches a character that cannot be considered part of a number, it strips out everything from that point on. So trying to compare "256abcd" to an integer column will result in actually comparing the number 256.

    So your options (or at least a few of them) would be: Validate the input string in your application code and reject it if it's not an integer (see the ctype_digit function in PHP). Change the column type for the filename if you want to treat it as a string (e.g. a VARCHAR type). Cast the column value to a string:

    . . . WHERE CAST(Id AS CHAR) = '256aei'
    

    Source

提交回复
热议问题