简体   繁体   English

sql 数字数据库列如何与数字字符串值一起使用

[英]How sql numeric db columns works with numeric string values

I have a question related to SQL.我有一个与 SQL 有关的问题。

I am recently coding an application, where sql query is generated dynamically based on user's inputs from UI.我最近正在编写一个应用程序,其中 sql 查询是根据用户从 UI 的输入动态生成的。 Interestingly list of values passed from UI were all of strings.有趣的是,从 UI 传递的值列表都是字符串。 I was told to add support of numeric values.有人告诉我要添加对数值的支持。 But what I noticed that passing numeric string value to numeric field also works.但我注意到将numeric string value传递给数字字段也有效。

for example:例如:

Select * from employee where id = 36815

and

Select * from employee where id = "36815"

My question is why second query work.我的问题是为什么第二个查询有效。 Even if I change = operator to < or > , it still works.即使我将=运算符更改为<> ,它仍然有效。 I want to know why it works and should we support it as it is.我想知道它为什么有效,我们是否应该支持它。 What can be disadvantages of using numeric string fields for numeric db columns.将数字字符串字段用于数字数据库列有什么缺点。

Thanks.谢谢。

Values in databases have types.数据库中的值有类型。 And, you should learn not to mix types in expressions -- particularly in where and on clauses -- because such mixing can confuse the optimizer.而且,您应该学会不要在表达式中混合类型——尤其是在whereon子句中——因为这种混合会使优化器感到困惑。

What is happening in your expression?你的表情发生了什么? The SQL compiler is seeing something like: SQL 编译器看到如下内容:

where <number> = <string>

By the rules of SQL, it says that the string needs to be converted to a number.按照SQL的规则,是说需要将字符串转为数字。 MySQL does this by converting leading digits. MySQL 通过转换前导数字来做到这一点。 So the result is something like:所以结果是这样的:

where <number> = cast(string as int)

(although non-integers are allowed). (尽管允许非整数)。

Note that this is not based on the string being a constant.请注意,这不是基于字符串是常量。 Only on the type of the columns.仅在列的类型上。 So, if the expression were:所以,如果表达式是:

where stringcol = 5

Then stringcol would be converted to a number.然后stringcol将被转换为数字。

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

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