使用select语句插入MySQL表

时间:2015-04-25 12:16:35

标签: mysql sql

我的MySQL表有三列十行:

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。

让我们看看这个例子。我想将新元素添加到Child #1 ID等于3ParentID等于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");

4 个答案:

答案 0 :(得分:1)

通常这需要通过应用程序级别完成,但是在同一个查询中,您可以使用insert into .. select from

insert into `tree`(`ID`, `Name`, `ParentID`)
select 
11,
"Inserted Element",
ParentID
from(
 select ParentID from tree where ID = 3
)x

答案 1 :(得分:1)

我不知道这种语法对你的数据库是否合法,但尝试类似这样的

INSERT INTO `tree`(`ID`, `Name`, `ParentID`) VALUES (11, "Inserted Element", (SELECT ParentID FROM tree 
WHERE id = 3));

答案 2 :(得分:1)

您可以使用insert select声明执行此操作:

insert into `tree`(`ID`, `Name`, `ParentID`)
select 11, "Inserted Element", `ParentID`
from `tree` where `ID` = 3

答案 3 :(得分:1)

Oracle's page about Look and Feels

INSERT INTO tree (id, name, parentID)
  SELECT 11, 'Inserted Element', parentID 
  FROM tree t 
  WHERE t.id = 3;
相关问题