gpt4 book ai didi

mysql - 为什么 `WHERE column` 给出的结果与 `WHERE column IS NOT NULL AND column <> ' '` 不同?

转载 作者:行者123 更新时间:2023-11-29 06:26:08 26 4
gpt4 key购买 nike

我有两列,area 和 block,其中 area 是一个 int 类型,block 是一个 varchar。

现在我正在写两个查询:

select * from table where area and block;

select * from table where area is not null and area <> ''
and block is not null and block <> '';

我在运行这些查询时得到了不同的结果集。它们之间可能有什么区别?

我认为上面一个返回区域和 block 都存在的地方,第二个应该返回相同的东西。

最佳答案

尽管 is not null,您的第二个查询的行为是正常的是多余的,因为 any arithmetic comparison with null gives null as the result .

这里的怪癖在于第一个查询。 MySQL 在隐式类型转换方面相当慷慨(无论好坏)。它处理一个没有 comparison function or operator 的裸表达式通过将求值表达式的值隐式转换为 bool 值作为有效谓词——在 MySQL 的世界中,is just an integer .

你的 block列是 varchar . MySQL 的 documentation page on type conversion显示当作为裸表达式谓词提供时,此列中的值将如何隐式转换为 bool 值(读作:整数):

The following examples illustrate conversion of strings to numbers for comparison operations:

mysql> SELECT 1 > '6x';
-> 0
mysql> SELECT 7 > '6x';
-> 1
mysql> SELECT 0 > 'x6';
-> 0
mysql> SELECT 0 = 'x6';
-> 1

这里隐含但未明确说明的是,如果字符串以数字开头,MySQL 会“猜测”这一定是您想要的数字;否则,它“猜测”为零。因此,如果 block 中的值恰好是 'a' ,第一个查询将隐式转换为 0并过滤掉该行,因为 WHERE area and 0永远不是真的。如果您来自一种在 bool 上下文中将非空字符串视为 true 的语言,这是非常出乎意料的!但是,嘿,这是 MySQL……一段时间后,您就会学会放弃期望。

第二个查询没有进行任何隐式转换,因为 the <> operator is actually testing inequality ; 'a'显然不等于 '' ,也不是 null ,因此两个谓词都为真,并且该行未从结果集中过滤掉。

关于mysql - 为什么 `WHERE column` 给出的结果与 `WHERE column IS NOT NULL AND column <> ' '` 不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30885007/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com