简体   繁体   English

带字符串搜索的MySQL整数列返回无效结果

[英]MySQL integer column with string search returns the invalid result

Can anyone please help me to understand the MySQL select query behavior and help me to solve this, 谁能帮助我了解MySQL选择查询行为并帮助我解决此问题,

How to show no results found message based on user search? 如何显示基于用户搜索的未找到结果的消息?

Table Structure: 表结构:

CREATE TABLE `dummytable` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `mobile` int(11) NOT NULL,
  `welcome` varchar(150) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=latin1

在此处输入图片说明

Question : Why I am getting this result? 问题 :为什么我得到这个结果?

SELECT * FROM `dummytable` WHERE `mobile` = '\'\'' LIMIT 50


在此处输入图片说明

The column mobile is declared as an integer. mobile列被声明为整数。 When MySQL compares an integer to a string, then it converts the string to a number -- not the other way around. 当MySQL将整数与字符串进行比较时,它将字符串转换为数字-而不是相反。

How does MySQL do this? MySQL如何做到这一点? It converts the leading numeric characters to a number. 它将前导数字字符转换为数字。 Your condition is: 您的条件是:

WHERE mobile = ''''

(The traditional SQL way to put a single quote in a string is to double it up.) (将单引号放在字符串中的传统SQL方法是将其加倍。)

The single quote is not a numeric character, so the conversion results in 0 . 单引号不是数字字符,因此转换结果为0 And hence, that is the result that you get. 因此,这就是您得到的结果。

Your column mobil is an integer column. 您的mobil列是一个整数列。 So everything is converted to int. 因此,一切都转换为int。 An empty string is converted to 0 (and any other string not starting with a number will also be converted to zero I think) 空字符串将转换为0(我认为其他不以数字开头的字符串也将转换为零)

After execution of this query MySQL shows you a warning message: 执行完该查询后,MySQL向您显示一条警告消息:

mysql> select * from foo where bar_integer='\'\''

....

10 rows in set, 1 warning (0.01 sec)

mysql> show warnings;
+---------+------+------------------------------------------+
| Level   | Code | Message                                  |
+---------+------+------------------------------------------+
| Warning | 1292 | Truncated incorrect DOUBLE value: 'okay' |
+---------+------+------------------------------------------+

MySQL tries to convert you string value to destination type (integer), if convertion fails mysql interprites it as 0 which results to what you see. MySQL会尝试将您的字符串值转换为目标类型(整数),如果转换失败,则mysql会将其值解释为0,这将得出您所看到的结果。

If you turn on MySQL strict mode this query would produce an error instead of making this implicit cast. 如果打开MySQL严格模式,此查询将产生错误,而不是进行隐式强制转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM