如何使用 MySQL COALESCE() 函数在 NULL 所在的位置向某一列中插入值?
要理解这一点,我们使用 `Employee` 表中的数据,对于 ID = 5 和 6,Salary = NULL,如下所示 −
mysql> Select * from Employee; +----+--------+--------+ | ID | Name | Salary | +----+--------+--------+ | 1 | Gaurav | 50000 | | 2 | Rahul | 20000 | | 3 | Advik | 25000 | | 4 | Aarav | 65000 | | 5 | Ram | NULL | | 6 | Mohan | NULL | +----+--------+--------+ 6 rows in set (0.00 sec)
现在,以下查询将使用 COALESCE() 函数以及 UPDATE 和 WHERE 子句,在 NULL 位置放置值。
mysql> Update Employee set Salary = COALESCE(Salary,20000) where Id = 5; Query OK, 1 row affected (0.09 sec) Rows matched: 1 Changed: 1 Warnings: 0 mysql> Update Employee set Salary = COALESCE(Salary,30000) where Id = 6; Query OK, 1 row affected (0.06 sec) Rows matched: 1 Changed: 1 Warnings: 0 mysql> Select * from Employee; +----+--------+--------+ | ID | Name | Salary | +----+--------+--------+ | 1 | Gaurav | 50000 | | 2 | Rahul | 20000 | | 3 | Advik | 25000 | | 4 | Aarav | 65000 | | 5 | Ram | 20000 | | 6 | Mohan | 30000 | +----+--------+--------+ 6 rows in set (0.00 sec)
广告