将表命名为categories

IdRows  |  CategoriesName |  UpperLevelName
--------------------------------------------
 1      |  SomeName       |


例如要插入第二行,如下所示

IdRows  |  CategoriesName |  UpperLevelName
--------------------------------------------
 2      |  SomeNameNext   |  SomeName


像这样查询

INSERT INTO categories (
CategoriesName,
UpperLevelName
)
VALUES (
?,
(SELECT CategoriesName FROM categories WHERE IdRows = ?)
)


我的意思是在UpperLevelName中要插入CategoriesName,其中IdRows = 1

但是得到错误You can't specify target table 'categories' for update in FROM clause

据了解错误在这里(SELECT CategoriesName FROM categories WHERE IdRows = ?)

什么是正确的代码?

最佳答案

insert ... select语法不包含values关键字。并且您需要建立一个临时表,因为在MySQL中您无法更新要从​​中选择的表

INSERT INTO categories (CategoriesName, UpperLevelName)
SELECT * from
(
   select ?, CategoriesName FROM categories WHERE IdRows = ?
) tmp

10-06 06:47