简体   繁体   English

SQL 查询给出错误结果

[英]SQL Query giving wrong results

The query executed should match the story_id with the provided string but when I execute the query it's giving me a wrong result.执行的查询应该将 story_id 与提供的字符串匹配,但是当我执行查询时,它给了我错误的结果。 Please refer to the screenshot.请参考截图。

在此处输入图片说明

story_id column in your case is of INT (or numeric) datatype.您的案例中的story_id列是INT (或数字)数据类型。

MySQL does automatic typecasting in this case.在这种情况下,MySQL 会自动进行类型转换。 So, 5bff82... gets typecasted to 5 and thus you get the row corresponding to story_id = 5所以, 5bff82...被类型转换为5 ,因此你得到对应于story_id = 5 的行

Type Conversion in Expression Evaluation表达式计算中的类型转换

When an operator is used with operands of different types, type conversion occurs to make the operands compatible.当运算符与不同类型的操作数一起使用时,会发生类型转换以使操作数兼容。 Some conversions occur implicitly.某些转换是隐式发生的。 For example, MySQL automatically converts strings to numbers as necessary, and vice versa.例如,MySQL 会根据需要自动将字符串转换为数字,反之亦然。

Now, ideally your application code should be robust enough to handle this input.现在,理想情况下,您的应用程序代码应该足够健壮以处理此输入。 If you expect the input to be numeric only, then your application code can use validation operations on the data (to ensure that it is only a number, without typecasting) before sending it to MySQL server.如果您希望输入仅为数字,那么您的应用程序代码可以在将数据发送到 MySQL 服务器之前对数据使用验证操作(以确保它只是一个数字,而不是类型转换)。

Another way would be to explicitly typecast story_id as string datatype and then perform the comparison.另一种方法是将story_id显式转换为字符串数据类型,然后执行比较。 However this is not recommended approach as this would not be able to utilize Indexing.然而,这不是推荐的方法,因为这将无法利用索引。

SELECT * FROM story
WHERE (CAST story_id AS CHAR(12)) = '5bff82...'

If you run the above query, you would get no results.如果您运行上述查询,您将不会得到任何结果。

you can also use smth like this:你也可以像这样使用 smth:

SELECT * FROM story
WHERE regexp_like(story_id,'^[1-5]{1}(.*)$');

for any story_ids starting with any number and matching any no of charatcers after that it wont match with story_id=5 ;对于以任何数字开头并匹配任何字符之后的任何 story_ids,它不会与story_id=5匹配; AND if you explicitly want to match it with a string;并且如果您明确想将其与字符串匹配;

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

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