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一样
- 连接数据库(补充知识)
使用命令行客户端的方式连接oracle数据库
sqlplus /nolog
conn shaoming/root@192.168.66.100:1521/orcl
conn 用户名/密码@ip地址:端口号(默认是1521)/服务名(服务明,默认是orcl)
注意
:端口号和服务名根据自己实际情况
- 测试建表脚本
create table demo ( id int , name varchar(64));
- 加入测试数据
insert into demo values(1,'root');
insert into demo values(2,'root2');
insert into demo values(1,null);
commit;
注意
:插入数据后要提交事务,因为oracle客户端不会自动提交事务,和mysql不一样的
- 几个测试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数据库测试
- 测试的建表脚本
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);
- 测试的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