sql中=null和is null区别

sql中=null和is null区别

前言

关于sql语句对null的处理尤其小心,这个null处理的知识点我看了好几次,但是很容易再次犯错,这次记录一个点,

因为这个错误是我看一个帖子看到的错误的写法

错误现场

-- 1、查询"01"课程比"02"课程成绩高的学生的信息及课程分数  
SELECT a.* ,b.s_score AS 01_score,c.s_score AS 02_score FROM 
    student a 
    JOIN score b ON a.s_id=b.s_id AND b.c_id='01'
    LEFT JOIN score c ON a.s_id=c.s_id AND c.c_id='02' OR c.c_id = NULL WHERE b.s_score>c.s_score

说明:

他其实表达的意思是去除c_id为null的数据,但是这样是不行的

oracle数据库测试

说明:

其实测试oracle主要为了回忆oracle基础知识,以及测试oracle对null值的处理是否和mysql一样

  1. 连接数据库(补充知识)

使用命令行客户端的方式连接oracle数据库

sqlplus /nolog 
conn shaoming/root@192.168.66.100:1521/orcl

conn 用户名/密码@ip地址:端口号(默认是1521)/服务名(服务明,默认是orcl)

注意:端口号和服务名根据自己实际情况

  1. 测试建表脚本
create table demo ( id int , name varchar(64));
  1. 加入测试数据
insert into demo values(1,'root');

insert into demo values(2,'root2');

insert into demo values(1,null);

commit;

注意:插入数据后要提交事务,因为oracle客户端不会自动提交事务,和mysql不一样的

  1. 几个测试sql
SQL> select * from demo;

        ID NAME
---------- ----------------------------------------------------------------
         1 root
         2 root2
         1

SQL> select * from demo where name is null;

        ID NAME
---------- ----------------------------------------------------------------
         1

SQL> select * from demo where name is not null;

        ID NAME
---------- ----------------------------------------------------------------
         1 root
         2 root2

SQL> select * from demo where name = null;

no rows selected

SQL> select * from demo where name != null;

no rows selected

mysql数据库测试

  1. 测试的建表脚本
CREATE TABLE `demo` (
  `id` int(11) DEFAULT NULL,
  `name` varchar(50) DEFAULT NULL
);
 insert into demo select 1 , 'root' from dual;
 insert into demo select 2 , 'root2' from dual;
 insert into demo (id) values(3);
  1. 测试的sql语句
MariaDB [test]> select * from demo ;
+------+-------+
| id   | name  |
+------+-------+
|    1 | root  |
|    2 | root2 |
|    3 | NULL  |
+------+-------+
3 rows in set (0.000 sec)

MariaDB [test]> select * from demo where name is null;
+------+------+
| id   | name |
+------+------+
|    3 | NULL |
+------+------+
1 row in set (0.000 sec)

MariaDB [test]> select * from demo where name is not null;
+------+-------+
| id   | name  |
+------+-------+
|    1 | root  |
|    2 | root2 |
+------+-------+
2 rows in set (0.000 sec)

MariaDB [test]> select * from demo where name = null;
Empty set (0.000 sec)

MariaDB [test]> select * from demo where name != null;
Empty set (0.000 sec)

总结

***在mysql和oracle中以下结论都是成立***

=null和!=null这种语法都是错误的

正确的用法是is null和is not null

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值