如果用于在 UPDATE 语句的 SET 子句中赋值的子查询没有返回任何行,MySQL 会返回什么?
在这种情况下,MySQL 将为 SET 子句提供 NULL 值。以下示例将演示它:
示例
mysql> Select * from student; +----+---------+-----------+ | Id | Name | grade | +----+---------+-----------+ | 1 | Rahul | Good | | 2 | Gaurav | Good | | 3 | Raman | Excellent | | 4 | Harshit | Average | | 5 | Aarav | Best | | 6 | Ram | average | +----+---------+-----------+ 6 rows in set (0.00 sec) mysql> select * from info; +------+-----------+ | id | remarks | +------+-----------+ | 1 | Good | | 2 | Good | | 3 | Excellent | | 4 | Average | | 5 | Best | +------+-----------+ 5 rows in set (0.00 sec)
从以上两个表中,我们可以看到“student”表有 6 行,其中 id = 6 的“grade”值为“average”,“info”表有 5 行。现在,以下查询中使用的子查询将不提供任何行来在 SET 子句中赋予新值,因此它将插入一个 NULL 值。这可以通过以下查询的结果来验证:
mysql> UPDATE STUDENT SET grade = (SELECT remarks from info WHERE info.id = student.id) WHERE id = 6; Query OK, 1 row affected (0.04 sec) Rows matched: 1 Changed: 1 Warnings: 0 mysql> Select * from student; +----+---------+-----------+ | Id | Name | grade | +----+---------+-----------+ | 1 | Rahul | Good | | 2 | Gaurav | Good | | 3 | Raman | Excellent | | 4 | Harshit | Average | | 5 | Aarav | Best | | 6 | Ram | NULL | +----+---------+-----------+ 6 rows in set (0.00 sec)
广告