我的 MySQL 表有 3 列和 10 行:
ID NAME ParentID
1 Parent #1 NULL
2 Child #1 1
3 Child #1 1
4 Child #1 1
5 Child #1 2
6 Child #1 2
7 Child #1 3
8 Child #1 3
9 Child #1 3
10 Child #1 3
在前端添加新元素后,我只得到这个新元素所属的父元素的ID。
让我们看例子。我想将新元素添加到具有 ID
等于 3
和 ParentID
的 Child #1
等于 1
。
从前端,我只得到 ID
值(例如上面示例中的 3
)。当我想将新元素插入表中时,我需要将此元素设置为正确的 ParentID
。我应该使用什么查询来实现这一目标?请查看我的以下查询:
INSERT INTO `tree` (`ID`, `Name`, `ParentID`)
VALUES (11, "The new element", "and here I'd like to give this new element the ParentID of the element with ID equals to 3");
最佳答案
您可以使用 insert select
语句执行此操作:
insert into `tree`(`ID`, `Name`, `ParentID`)
select 11, "Inserted Element", `ParentID`
from `tree` where `ID` = 3
关于mysql - 使用 select 语句插入 MySQL 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29865038/