为什么`WHERE列'给出的结果不同于`​​WHERE列IS NOT NULL AND列<> ''`?

时间:2015-06-17 07:29:55

标签: mysql

我有两个列,区域和块,其中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 <> '';

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

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

1 个答案:

答案 0 :(得分:2)

您的第二个查询的行为是正常的,但is not nullany arithmetic comparison with null gives null as the resultblock是多余的。

这里的怪癖是在第一个查询中。使用隐式类型转换,MySQL非常慷慨(无论好坏)。它通过将计算表达式的值隐式转换为布尔值来处理一个没有comparison function or operator的裸表达式作为有效谓词 - 在MySQL的世界中,is just an integer

您的varchar列是mysql> SELECT 1 > '6x'; -> 0 mysql> SELECT 7 > '6x'; -> 1 mysql> SELECT 0 > 'x6'; -> 0 mysql> SELECT 0 = 'x6'; -> 1 。 MySQL的documentation page on type conversion显示了当作为裸表达式谓词提供时,此列中的值将如何隐式转换为布尔值(读取:整数):

  

以下示例说明了将字符串转换为数字   比较操作:

block

这里暗示的是,但是没有明确说明,如果字符串以数字开头,则MySQL“猜测”必须是您想要的数字;否则,它 “猜测”为零。因此,如果'a'中的值恰好是0,则第一个查询将隐式地将其转换为WHERE area and 0并过滤掉该行,因为'a'永远不会为真。如果您来自在布尔上下文中将非空字符串视为true的语言,那么这是非常意外的!但是,嘿,这是MySQL ......过了一段时间,你学会放下期望。

第二个查询不执行任何隐式转换,因为the <> operator is actually testing inequality; ''显然不等于null,也不是Using properties file: null Using properties file: null Parsed arguments: master yarn-master deployMode cluster executorMemory 512m executorCores null totalExecutorCores null propertiesFile null extraSparkProperties Map() driverMemory null driverCores null driverExtraClassPath null driverExtraLibraryPath null driverExtraJavaOptions null supervise false queue null numExecutors 3 files null pyFiles null archives null mainClass com.foo.bar.spark.examples.WordCountSparkJob primaryResource hdfs://sandbox.hortonworks.com:8020/apps/foo/sandbox.hortonworks.com/1.201-SNAPSHOT/oozieapp/lib/abc-1.201-SNAPSHOT.jar name Spark Example childArgs [inputpath=hdfs://sandbox.hortonworks.com:8020/tmp/bcp_examples/input/] jars null verbose true Default properties from null: Error: Could not load YARN classes. This copy of Spark may not have been compiled with YARN support. Run with --help for usage help or --verbose for debug output Intercepting System.exit(-1) Failing Oozie Launcher, Main class [org.apache.oozie.action.hadoop.SparkMain], exit code [-1] ,因此两个谓词都为真,并且不会从结果集中过滤行。

相关问题