解决Mysql同一个表不能同时进行update和select操作的问题

我要更改帝国CMS栏目ID=583的下级栏目模板ID,用下面SQL语句,没毛病:

UPDATE `phome_enewsclass` SET `listtempid` = 2 WHERE bclassid = 583

我要更改帝国CMS栏目ID=583的下下级栏目模板ID,用下面SQL语句:

UPDATE `phome_enewsclass` SET `listtempid` = 2 WHERE bclassid in (SELECT classid FROM `phome_enewsclass` WHERE bclassid = 583)

执行报错:#1093 - You can't specify target table 'phome_enewsclass' for update in FROM clause,意思是在同一张表上,你不能先select了再执行update操作。

改用下面SQL语句,可以修改指定栏目下的第三级栏目的模板ID:

UPDATE `phome_enewsclass` AS A INNER JOIN (SELECT classid FROM `phome_enewsclass` WHERE bclassid in(SELECT classid FROM `phome_enewsclass` WHERE bclassid = 583)) AS B ON A.classid = B.classid SET A.listtempid = 2

添加新评论