简体   繁体   English

Mysql 查询返回错误结果

[英]Mysql query is returning false results

I have a products table with a product_id field that is an auto-ID and an integer.我有一个产品表,其中的 product_id 字段是自动 ID 和 integer。 When I search:当我搜索时:

SELECT * FROM `products` WHERE product_id = '73N716507Y5928128'

it actually returns the row whose product_id is 73. And I may be new to programming but I KNOW that 73.= 73N716507Y5928128.它实际上返回 product_id 为 73 的行。我可能是编程新手,但我知道 73.= 73N716507Y5928128。

What can I do to fix this?我能做些什么来解决这个问题? The reason BTW for this query is that I am searching multiple tables and multiple fields for a search term and using logic to determine what the user is searching for...顺便说一句,这个查询的原因是我在多个表和多个字段中搜索一个搜索词,并使用逻辑来确定用户正在搜索什么......

Any help would be greatly appreciated.任何帮助将不胜感激。

In mysql, when you compare (=, <, >, <=, >=, <=>) a numeric field and a character field, the character field is converted to a number first, disregarding any trailing non-numeric characters.在 mysql 中,当您比较(=、<、>、<=、>=、<=>)一个数字字段和一个字符字段时,字符字段首先转换为数字,忽略任何尾随的非数字字符。

Presumably you want the product_id= part to stay unchanged to take advantage of an index.大概您希望product_id=部分保持不变以利用索引。 You can add an additional condition to test if the input is in fact a number:您可以添加一个附加条件来测试输入是否实际上是一个数字:

SELECT * FROM `products`
WHERE product_id = '73N716507Y5928128'
AND CONCAT(0+'73N716507Y5928128')='73N716507Y5928128';

Your business logic should ensure that only integers are passed in the where clause .您的业务逻辑应确保在where clause中仅传递整数。 However, you may also try the following, it will fix the issue.但是,您也可以尝试以下方法,它会解决问题。 But if products table has millions of records, this will not be a good idea due to table full scan.但是如果products表有数百万条记录,由于表全扫描,这将不是一个好主意。 But if there are say 10K or less products in the table, full scan will not be significant at all.但是,如果表中有 10K 或更少的产品,那么全扫描将根本没有意义。

SELECT * FROM `products` WHERE binary(product_id) = '73N716507Y5928128'

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

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