mySQL returns all rows when field=0

后端 未结 4 832
孤街浪徒
孤街浪徒 2020-11-30 08:55

I was making some tests, and it was a surprise when i was querying a table, and the query SELECT * FROM table WHERE email=0 returned all rows from the table.

4条回答
  •  难免孤独
    2020-11-30 09:40

    Your email column is a CHAR or VARCHAR type. When you use the condition email = 0, MySQL is casting the contents of the email column to an integer in order to compare them with the 0 you supplied. Had you surrounded your 0 in quotes, the query would work as expected. (email = '0')

    Converting a non-numeric string to an integer in MySQL will result in 0.

    mysql> SELECT CAST('email@example.com' AS SIGNED);
    +-------------------------------------+
    | CAST('email@example.com' AS SIGNED) |
    +-------------------------------------+
    |                                   0 |
    +-------------------------------------+
    

    In contrast, if you attempted the same thing with numeric strings, they may cast correctly:

    mysql> SELECT CAST('12345' AS SIGNED);
    +-------------------------+
    | CAST('12345' AS SIGNED) |
    +-------------------------+
    |                   12345 |
    +-------------------------+
    

提交回复
热议问题