有什么区别
where x is null
Run Code Online (Sandbox Code Playgroud)
和
where x = null
Run Code Online (Sandbox Code Playgroud)
为什么后者不起作用?
Boh*_*ian 124
在SQL中,之间的比较null值,任何其他值(包括另一种null使用比较操作符(如)=,!=,<,等)将导致null,这被认为是false一个where子句的目的(严格来说,它的"不真的",而不是"假",但效果是一样的).
理由是一种null手段"未知",因此任何与a的比较结果null也是"未知".因此,您不会通过编码获得行数where my_column = null.
SQL提供了一种特殊的语法,用于测试列是否是null通过is null和is not null,这是测试null(或不是a null)的特殊条件.
这里有一些SQL显示了各种条件及其效果.
create table t (x int, y int);
insert into t values (null, null), (null, 1), (1, 1);
select 'x = null' as test , x, y from t where x = null
union all
select 'x != null', x, y from t where x != null
union all
select 'not (x = null)', x, y from t where not (x = null)
union all
select 'x = y', x, y from t where x = y
union all
select 'not (x = y)', x, y from t where not (x = y);
Run Code Online (Sandbox Code Playgroud)
只返回1行(如预期的那样):
TEST X Y
x = y 1 1
Run Code Online (Sandbox Code Playgroud)
看看这个在SQLFiddle上运行
Cur*_*urt 59
值得注意的是,NULL不等于NULL.
NULL 不是值,因此无法与其他值进行比较.
where x is null 检查x是否为空值.
where x = null 正在检查x是否等于NULL,这将永远不会成立
首先是检查字段值是否正确的正确方法null以后将不会按照您期望的方式工作,因为null特殊值不等于任何东西,因此您不能使用相等比较=.
因此,当您需要检查字段值是否null存在时,请使用:
where x is null
Run Code Online (Sandbox Code Playgroud)
代替:
where x = null
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
105278 次 |
| 最近记录: |