MySQL ifnull函式判斷欄位值為null時使用預設值
阿新 • • 發佈:2019-01-29
在使用left join等聯表查詢時,常遇到某些欄位為null,一般都在後臺語言使用if a==null 判斷做處理,其實MySQL本身也有一個ifnull函式可以處理。
假設有兩張表
name表:
1 2 3 4 5 6 7 8 9 10 |
mysql> select
* from name;
+------+-----------+
| id
| user |
+------+-----------+
| 1 | xiaoqiang |
| 2 | lisi |
| 3 | xiaowu |
| 4 | laoliu | +------+-----------+
4 rows in
set (0.00 sec)
|
phone表:
1 2 3 4 5 6 7 8 |
mysql> select
* from phone;
+------+-------+
| id
| phone |
+------+-------+
| 2 | 110 |
| 3 | 119 |
+------+-------+
2 rows in
set (0.00 sec)
|
聯表查詢結果:
1 2 3 4 5 6 7 8 9 10 |
mysql> select
a.*,b.phone from name a left join
phone b on a. id =b. id ;
+------+-----------+-------+
| id
| user | phone |
+------+-----------+-------+
| 1 | xiaoqiang | NULL |
| 2 | lisi | 110 |
| 3 | xiaowu | 119 |
| 4 | laoliu | NULL |
+------+-----------+-------+
4 rows in
set (0.01 sec)
|
其中id=1、id=4兩行的phone值為null,我們可以使用ifnull函式判斷它為null時給一個預設值:
1 2 3 4 5 6 7 8 9 10 |
mysql> select
a.*,ifnull(b.phone,0) from name a left join
phone b on a. id =b. id ;
+------+-----------+-------------------+
| id
| user | ifnull(b.phone,0) |
+------+-----------+-------------------+
| 1 | xiaoqiang | 0 |
| 2 | lisi | 110 |
| 3 | xiaowu | 119 |
| 4 | laoliu | 0 |
+------+-----------+-------------------+
4 rows in
set (0.00 sec)
|
甚至也可以指定某一個欄位值來填補
1 2 3 4 5 6 7 8 9 10 |
mysql> select
a.*,ifnull(b.phone,a. id ) from name a left
join phone b on a. id =b. id ;
+------+-----------+----------------------+
| id
| user | ifnull(b.phone,a. id ) |
+------+-----------+----------------------+
| 1 | xiaoqiang | 1 |
| 2 | lisi | 110 |
| 3 | xiaowu | 119 |
| 4 | laoliu | 4 |
+------+-----------+----------------------+
4 rows in
set (0.00 sec)
|
當b.phone的值為null時,使用name表中的id欄位來填補。但使用ifnull後列名看起來很不友好,可以用as還原
1 2 3 4 5 6 7 8 9 10 |
mysql> select
a.*,ifnull(b.phone,a. id ) as phone from name a left
join phone b on a. id =b. id ;
+------+-----------+-------+
| id
| user | phone |
+------+-----------+-------+
| 1 | xiaoqiang | 1 |
| 2 | lisi | 110 |
| 3 | xiaowu | 119 |
| 4 | laoliu | 4 |
+------+-----------+-------+
|