检查MySQL中的字段是空还是空?
NULL和空字符串''在MySQL中都不相似。要检查字段是否为空值(例如''或为null),您需要使用IS NULL属性或其他方式。您可以使用CASE语句检查所有条件。语法如下:
SELECT *, CASEWHEN yourColumnName =’ ‘ THEN ‘yourMessage1’
WHEN yourColumnName IS NULL THEN ‘yourMessage2’
ELSE CONCAT(yourColumnName ,' is a Name')
END AS anyVariableName
FROM yourTableName;
为了理解上述语法,让我们创建一个表。创建表的查询如下:
mysql> create table checkFieldDemo-> (
-> Id int NOT NULL AUTO_INCREMENT,
-> Name varchar(10),
-> PRIMARY KEY(Id)
-> );
使用insert命令在表中插入一些记录。查询如下:
mysql> insert into checkFieldDemo(Name) values(NULL);mysql> insert into checkFieldDemo(Name) values('John');
mysql> insert into checkFieldDemo(Name) values(NULL);
mysql> insert into checkFieldDemo(Name) values('');
mysql> insert into checkFieldDemo(Name) values('Carol');
mysql> insert into checkFieldDemo(Name) values('');
mysql> insert into checkFieldDemo(Name) values(NULL);
使用select语句显示表中的所有记录。查询如下:
mysql> select *from checkFieldDemo;
以下是输出:
+----+-------+| Id | Name |
+----+-------+
| 1 | NULL |
| 2 | John |
| 3 | NULL |
| 4 | |
| 5 | Carol |
| 6 | |
| 7 | NULL |
+----+-------+
7 rows in set (0.00 sec)
这是查询要检查的字段为空还是null或其他使用case语句的查询。查询如下:
mysql> select *,case-> when Name='' then 'It is an empty string'
-> when Name is null then 'It is a NULL value'
-> else concat(Name,' is a Name')
-> END as ListOfValues
-> from checkFieldDemo;
以下是输出:
+----+-------+-----------------------+| Id | Name | ListOfValues |
+----+-------+-----------------------+
| 1 | NULL | It is a NULL value |
| 2 | John | John is a Name |
| 3 | NULL | It is a NULL value |
| 4 | | It is an empty string |
| 5 | Carol | Carol is a Name |
| 6 | | It is an empty string |
| 7 | NULL | It is a NULL value |
+----+-------+-----------------------+
7 rows in set (0.00 sec)
以上是 检查MySQL中的字段是空还是空? 的全部内容, 来源链接: utcz.com/z/330903.html