MySql学习之”You can't specify target table 'book' for update in FROM clause“错误解决

时间:2021-02-20 08:24:56

  今天在写一个案例的时候,想通过多表查询来实现一个功能,写好了sql语句,执行后出现了You can't specify target table 'book' for update in FROM clause的错误。

  错误代码示例:

  

1 UPDATE book
2 SET amount = amount + (4 SELECT num FROM borrow WHERE uid = (
5 SELECT id FROM USER WHERE NAME = '健健' )
6 AND bid = (
7 SELECT id FROM book WHERE bookname = '平凡的世界'
8 )
9 )WHERE bookname = '平凡的世界';

 

 You can't specify target table 'book' for update in FROM clause:这句话翻译过来是:不能用同一表中查询的数据作为同一表的更新字段的参数值。

 痛过查询资料的知,这是因为mysql本身不支持这种写法,即使我们的逻辑都是对的,所以,只需要做一个小小的修改即可,在查询的时候,我们在更新和查询之间添加一个中间表,避免两张表之间的直接操作即可,下面是我修改之后的代码:

  

1 UPDATE book
2 SET amount = amount + (
3 SELECT a.num FROM(
4 SELECT num FROM borrow WHERE uid = (
5 SELECT id FROM USER WHERE NAME = '健健' )
6 AND bid = (
7 SELECT id FROM book WHERE bookname = '平凡的世界' ) ) a
8 )WHERE bookname = '平凡的世界';