简体   繁体   English

SQL如何处理int/string操作数与列之间的转换

[英]How does SQL handle conversion between int / string operand and column

I am trying to understand how comparison is done when the operand is integer and column type is string and vice versa.我试图了解当操作数为整数且列类型为字符串时如何进行比较,反之亦然。

Sample table样品表

My table is as follows:我的表如下:

mysql> DESCRIBE tbl1;
+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| col1  | varchar(255) | YES  |     | NULL    |       |
| col2  | int(11)      | YES  |     | NULL    |       |
| col3  | int(11)      | YES  |     | NULL    |       |
| col4  | varchar(255) | YES  |     | NULL    |       |
+-------+--------------+------+-----+---------+-------+

Its content is as follows:其内容如下:

mysql> SELECT * FROM tbl1;
+------+------+------+------+
| col1 | col2 | col3 | col4 |
+------+------+------+------+
| val1 | NULL |    7 | 7    |
| val4 | NULL | NULL | abc  |
| val2 |    2 |    8 | 8    |
| val3 |    3 |   18 | 18   |
+------+------+------+------+

Some queries一些查询

  1. Comparing string with INT column:将字符串与 INT 列进行比较:

     mysql> SELECT * FROM tbl1 WHERE "9" > col3; +------+------+------+------+ | col1 | col2 | col3 | col4 | +------+------+------+------+ | val1 | NULL | 7 | 7 | | val2 | 2 | 8 | 8 | +------+------+------+------+
  2. Comparing integer with VARCHAR column:将整数与 VARCHAR 列进行比较:

     mysql> SELECT * FROM tbl1 WHERE 9 > col4; +------+------+------+------+ | col1 | col2 | col3 | col4 | +------+------+------+------+ | val1 | NULL | 7 | 7 | | val4 | NULL | NULL | abc | | val2 | 2 | 8 | 8 | +------+------+------+------+

Doubts疑问

  1. Does SQL correctly converts between integer opreand / column and string operand / column before performing any comparison / mathematical operation?在执行任何比较/数学运算之前,SQL 是否正确地在整数操作数/列和字符串操作数/列之间进行转换? Is there any exception / detail to it?有什么例外/细节吗?
  2. Why second query returned row with col4 having abc ?为什么第二个查询返回带有abc col4行?

PS: I am not talking in the context of any specific database. PS:我不是在任何特定数据库的上下文中谈论。 So, if there is any database specific details / behavior variation to it, please share.因此,如果有任何特定于数据库的详细信息/行为变化,请分享。

When an integer is compared to a string, the sting is converted to a number.将整数与字符串进行比较时,字符串将转换为数字。

The number is based on the leading digits of the string.该数字基于字符串的前导数字。 If the string has no digits, then the value is treated as 0 .如果字符串没有数字,则该值被视为0

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

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