在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)

更新於: 2019年7月30日

9K+ 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.