如何使用 MySQL COALESCE() 函数在 NULL 的位置向某列中插入一个值?
为了理解它,我们使用表的收入=NULL的数据根据 ID,如下所示 −
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)
广告