Heim  >  Artikel  >  Datenbank  >  MySQL update嵌套

MySQL update嵌套

WBOY
WBOYOriginal
2016-06-07 17:27:281166Durchsuche

当我们想从MySQL中的表table1中取出id=5的列col1(例如: 博客当前访问量)中的数据d1, 并将table1的属性p1更新为d1+1的时候, 我们也

当我们想从MySQL中的表table1中取出id=5的列col1(例如: 博客当前访问量)中的数据d1, 并将table1的属性p1更新为d1+1的时候, 我们也许会想到使用这条SQL语句

update table1 set col1=(select col1 from a where id=5)+1 where id=5;

但在 MySQL 命令列工具中传回:

ERROR 1093 (HY000): You can't specify target table 'forum_members' for update in FROM clause

原来数据库都有这个规定:不允许UPDATE的子查询里面有被UPDATE的那个表。也就是说update a 的时候 不能在后面select col from a ,如果是不同表操作是没有问题的。想到一个解决方法:

UPDATE table1 a

INNER JOIN table1 b ON b.id=1 AND a.id=b.id

SET a.col=b.col+1

linux

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn