在MySQL中如何从两列中选择非空列?
有很多方法可以从两列中选择非空列。语法如下所示
**案例1**: 使用IFNULL()函数。
语法如下所示
SELECT IFNULL(yourColumnName1,yourColumnName2) as anyVariableName from yourTableName;
**案例2**: 使用coalesce()函数。
语法如下所示
SELECT COALESCE(yourColumnName1,yourColumnName2) as anyVariableName from yourTableName;
**案例3**: 使用CASE语句。
语法如下所示
SELECT CASE WHEN yourColumnName1 IS NOT NULL THEN yourColumnName1 ELSE yourColumnName2 END AS anyVariableName FROM yourTableName;
**案例4**: 只使用IF()。
语法如下所示
SELECT IF (yourColumnName1 ISNULL,yourColumnName2,yourColumnName1) AS NotNULLValue FROM SelectNotNullColumnsDemo;
为了理解上述语法,让我们创建一个表。创建表的查询如下所示
mysql> create table SelectNotNullColumnsDemo -> ( -> Id int NOT NULL AUTO_INCREMENT, -> Name varchar(20), -> Age int -> , -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (0.86 sec)
使用insert命令在表中插入一些记录。查询如下所示
mysql> insert into SelectNotNullColumnsDemo(Name,Age) values('John',NULL); Query OK, 1 row affected (0.16 sec) mysql> insert into SelectNotNullColumnsDemo(Name,Age) values(NULL,23); Query OK, 1 row affected (0.16 sec)
使用select语句显示表中的所有记录。查询如下所示
mysql> select *from SelectNotNullColumnsDemo;
输出如下所示
+----+------+------+ | Id | Name | Age | +----+------+------+ | 1 | John | NULL | | 2 | NULL | 23 | +----+------+------+ 2 rows in set (0.00 sec)
以下是从两列中选择非空值的查询。
**案例1**: IFNULL()
查询如下所示
mysql> select ifnull(Name,Age) as NotNULLValue from SelectNotNullColumnsDemo;
输出如下所示
+--------------+ | NotNULLValue | +--------------+ | John | | 23 | +--------------+ 2 rows in set (0.00 sec)
**案例2**: Coalesce
查询如下所示
mysql> select coalesce(Name,Age) as NotNULLValue from SelectNotNullColumnsDemo;
输出如下所示
+--------------+ | NotNULLValue | +--------------+ | John | | 23 | +--------------+ 2 rows in set (0.00 sec)
案例3: CASE
查询如下所示
mysql> select case -> when Name is not null then Name else Age -> end as NotNULLValue -> from SelectNotNullColumnsDemo;
输出如下所示
+--------------+ | NotNULLValue | +--------------+ | John | | 23 | +--------------+ 2 rows in set (0.00 sec)
**案例4**: IF()
查询如下所示
mysql> select if(Name is NULL,Age,Name) as NotNULLValue from SelectNotNullColumnsDemo;
输出如下所示
+--------------+ | NotNULLValue | +--------------+ | John | | 23 | +--------------+ 2 rows in set (0.00 sec)
广告