MySQL 语法在存在 null 的情况下不使用不等于运算符进行计算?
mysqlmysqli database
使用 IS NOT NULL 运算符与 NULL 值进行比较。语法如下 −
SELECT *FROM yourTableName where yourColumnName1 is not null or yourColumnName2 <> anyIntegerValue;
为了检查是否存在 null 不等于,让我们创建一个表。创建表的查询如下 −
mysql> create table IsNullDemo −> ( −> ProductId int, −> ProductName varchar(100), −> ProductBackOrder int −> ); Query OK, 0 rows affected (0.54 sec)
在表中插入一些含有空值的记录,以避免出现空值。插入记录的查询如下 −
mysql> insert into IsNullDemo values(100,'First-Product',null); Query OK, 1 row affected (0.14 sec) mysql> insert into IsNullDemo values(101,'Second-Product',2); Query OK, 1 row affected (0.22 sec) mysql> insert into IsNullDemo values(102,'Third-Product',null); Query OK, 1 row affected (0.20 sec) mysql> insert into IsNullDemo values(103,'Fourth-Product',4); Query OK, 1 row affected (0.17 sec) mysql> insert into IsNullDemo values(104,'Fifth-Product',10); Query OK, 1 row affected (0.17 sec) mysql> insert into IsNullDemo values(105,'Sixth-Product',null); Query OK, 1 row affected (0.20 sec)
使用 select 语句显示表中的所有记录。显示所有记录的查询如下−
mysql> select *from IsNullDemo;
以下是输出 −
+-----------+----------------+------------------+ | ProductId | ProductName | ProductBackOrder | +-----------+----------------+------------------+ | 100 | First-Product | NULL | | 101 | Second-Product | 2 | | 102 | Third-Product | NULL | | 103 | Fourth-Product | 4 | | 104 | Fifth-Product | 10 | | 105 | Sixth-Product | NULL | +-----------+----------------+------------------+ 6 rows in set (0.00 sec)
情况1:
这里是避免出现 null 的查询。查询如下 −
mysql> select *from IsNullDemo −> where ProductBackOrder is not null or ProductBackOrder <> 2;
以下是输出 −
+-----------+----------------+------------------+ | ProductId | ProductName | ProductBackOrder | +-----------+----------------+------------------+ | 101 | Second-Product | 2 | | 103 | Fourth-Product | 4 | | 104 | Fifth-Product | 10 | +-----------+----------------+------------------+ 3 rows in set (0.03 sec)
情况 2:
每当您希望存在 null(或不等于 2)时,请使用 IS NULL 概念。查询如下 −
mysql> select *from IsNullDemo −> where ProductBackOrder is null or ProductBackOrder <> 2;
以下是输出 −
+-----------+----------------+------------------+ | ProductId | ProductName | ProductBackOrder | +-----------+----------------+------------------+ | 100 | First-Product | NULL | | 102 | Third-Product | NULL | | 103 | Fourth-Product | 4 | | 104 | Fifth-Product | 10 | | 105 | Sixth-Product | NULL | +-----------+----------------+------------------+ 5 rows in set (0.00 sec)