为了使用另一个MySQL表中的值更新一个MySQL表中的值,我们需要在UPDATE语句的SET子句中使用子查询作为表达式。
在此示例中,我们有两个表“ student”和“ info”。我们将使用“信息”表的“备注”列中的值来更新表“学生”的“成绩”列中的值。
mysql> select * from student; +----+---------+-------+ | Id | Name | grade | +----+---------+-------+ | 1 | Rahul | NULL | | 2 | Gaurav | NULL | | 3 | Raman | NULL | | 4 | Harshit | NULL | | 5 | Aarav | NULL | +----+---------+-------+ 5 rows in set (0.01 sec) mysql> select * from info; +------+-----------+ | id | remarks | +------+-----------+ | 1 | Good | | 2 | Good | | 3 | Excellent | | 4 | Average | | 5 | Best | +------+-----------+ 5 rows in set (0.00 sec) mysql> UPDATE STUDENT SET grade = (SELECT remarks from info WHERE info.id = student.id) WHERE id > 0; Rows matched: 5 Changed: 5 Warnings: 0
上面的查询借助子查询来更新“学生”表的“成绩”列中的值。可以从以下MySQL查询返回的结果集中观察到它。
mysql> Select * from student; +----+---------+-----------+ | Id | Name | grade | +----+---------+-----------+ | 1 | Rahul | Good | | 2 | Gaurav | Good | | 3 | Raman | Excellent | | 4 | Harshit | Average | | 5 | Aarav | Best | +----+---------+-----------+ 5 rows in set (0.00 sec)