使用NOT IS NULL和TRIM()
function选择非空列值。语法如下。
SELECT * FROM yourTableName WHERE yourColumnName IS NOT NULL AND TRIM(yourColumnName) <> ' ';
您可以使用相同的TRIM()
方法从列中选择非空值以及空格。
为了理解上面讨论的语法,让我们创建一个表。创建表的查询如下-
mysql> create table SelectNonEmptyValues -> ( -> Id int not null auto_increment, -> Name varchar(30), -> PRIMARY KEY(Id) -> );
使用insert命令在表中插入记录。查询如下-
mysql> insert into SelectNonEmptyValues(Name) values('John Smith'); mysql> insert into SelectNonEmptyValues(Name) values(NULL); mysql> insert into SelectNonEmptyValues(Name) values(''); mysql> insert into SelectNonEmptyValues(Name) values('Carol Taylor'); mysql> insert into SelectNonEmptyValues(Name) values('DavidMiller'); mysql> insert into SelectNonEmptyValues(Name) values(' ');
使用select语句显示表中的所有记录-
mysql> select *from SelectNonEmptyValues;
以下是输出-
+----+-----------------------+ | Id | Name | +----+-----------------------+ | 1 | John Smith | | 2 | NULL | | 3 | | | 4 | Carol Taylor | | 5 | DavidMiller | | 6 | | +----+-----------------------+ 6 rows in set (0.00 sec)
这是选择非空值的查询。以下查询适用于所有情况-如果该列具有NULL,空字符串或空白-
mysql> SELECT * FROM SelectNonEmptyValues WHERE Name IS NOT NULL AND TRIM(Name) <> '';
以下是输出-
+----+--------------+ | Id | Name | +----+--------------+ | 1 | John Smith | | 4 | Carol Taylor | | 5 | DavidMiller | +----+--------------+ 3 rows in set (0.00 sec)