在 MySQL 中为单个列实现两个条件,针对 null 和空值


让我们首先创表 −

mysql> create table DemoTable635(
   EmployeId int NOT NULL AUTO_INCREMENT PRIMARY KEY,EmployeeName varchar(100)
);
Query OK, 0 rows affected (1.24 sec)

使用 insert 命令插入一些记录到表 −

mysql> insert into DemoTable635(EmployeeName) values('John');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable635(EmployeeName) values('Sam');
Query OK, 1 row affected (0.27 sec)
mysql> insert into DemoTable635(EmployeeName) values('');
Query OK, 1 row affected (0.38 sec)
mysql> insert into DemoTable635(EmployeeName) values(null);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable635(EmployeeName) values('David');
Query OK, 1 row affected (0.22 sec)

使用 select 语句显示表中的所有记录 −

mysql> select *from DemoTable635;

这会产生以下输出 −

+-----------+--------------+
| EmployeId | EmployeeName |
+-----------+--------------+
|         1 | John         |
|         2 | Sam          |
|         3 |              |
|         4 | NULL         |
|         5 | David        |
+-----------+--------------+
5 rows in set (0.00 sec)

以下是避免在 MySQL 列中显示空值的方法 −

mysql> select *from DemoTable635 tbl where tbl.EmployeeName is not null and tbl.EmployeeName <> '';

这会产生以下输出 −

+-----------+--------------+
| EmployeId | EmployeeName |
+-----------+--------------+
|         1 | John         |
|         2 | Sam          |
|         5 | David        |
+-----------+--------------+
3 rows in set (0.02 sec)

更新于: 2019-08-23

113 次浏览

开启您的 职业生涯

通过完成课程获取认证

开始
广告