mysql query showing wrong result

佐手、 提交于 2020-05-24 03:35:06

问题


I have a database table look like this

+======+===========+============+
|  ID  | user Name |user surname|
+======+===========+============+
| 100  |  name     |  surname   |
| 101  |  name     |  surname   |
| 102  |  name     |  surname   |
+===============================+

When i run this query which should show me no rows because there is no row with 101foo2 value :

SELECT * FROM tableName WHERE ID = '101foo2'

I am getting a result with same ID without the foo2 word

+======+===========+============+
|  ID  | user Name |user surname|
+======+===========+============+
| 101  |  name     |  surname   |
+===============================+

how it is showing the row with ID 101 if my query is ID = '101foo2'


回答1:


You are mixing types. ID is an integer (or number). You are comparing it to a string. So, MySQL needs to decide what type to use for the comparison. What types gets used? Well, a string? No. A number. The string is converted to a number, using the leading digits. So, it becomes 101 and matches.

You should really only compare numbers to numbers, and strings to strings. You could try to write the code as:

SELECT * FROM tableName WHERE ID = 101foo2

However, you would get an error. Another possibility is to force the conversion to a string:

SELECT * FROM tableName WHERE CAST(ID as CHAR) = '101foo2'


来源:https://stackoverflow.com/questions/54026797/mysql-query-showing-wrong-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!