我很想知道这些查询在数据库引擎中如何工作。特别是我的重点是第 4 行和第 6 行。
1.SELECT * FROM tableName
2.SELECT * FROM tableName WHERE 1
3.SELECT * FROM tableName WHERE 123
4.SELECT * FROM tableName WHERE '2xyz'
5.SELECT * FROM tableName WHERE ''
6.SELECT * FROM tableName WHERE 'xyz'
在上面的查询中,1、2、3、4 产生相同的结果,但 5 和 6 没有产生任何结果。为什么?什么是 diff b/w WHERE '2xyx' 和 'xyz'? '2xyz' 如何隐式转换为 2 ?
最佳答案
where
子句的计算结果为 bool 值 true(非 0)或 false(0),以便确定记录是否位于结果集中或之外。
情况 2 和 3 会检索所有记录,因为非零数字的计算结果为 true。
情况 3 检索所有记录,因为在隐式字符串到数字转换期间,mysql 从左到右逐个字符地评估字符串。只要字符可以被评估为数字,mysql就会取它们的值。这包括删除前导空格、解释加号或减号、小数点等。因此,字符串
'2xyx'
被解释为 2,即 bool 值 true。情况 4 和 5 不会检索任何记录,因为字符串最左边的字符无法计算为数字,因此转换返回 0,即 bool 值 false。
不幸的是,MySQL 手册中并未真正记录隐式字符串到数字的转换。不过,大部分规则都可以从Type Conversion in Expression Evaluation中的以下部分中推导出来。手册部分:
For comparisons of a string column with a number, MySQL cannot use an index on the column to look up the value quickly. If str_col is an indexed string column, the index cannot be used when performing the lookup in the following statement:
SELECT * FROM tbl_name WHERE str_col=1;1
The reason for this is that there are many different strings that may convert to the value 1, such as '1', ' 1', or '1a'.
关于mysql - SELECT * FROM 表名 WHERE 'num+sometext',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48942263/