简体   繁体   中英

Insert into MySQL table with select statement

My MySQL table has three columns and ten rows:

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

After adding the new element on the front-end, I am getting only the parent's ID to which this new element belongs to.

Let's see the example. I'd like to add the new element to the Child #1 that has ID equals to 3 and ParentID equals to 1 .

From the front-end, I get only the ID value (eg 3 in our example above). When I'd like to insert the new element into the table, I need to set this element the right ParentID . What query should I use to achieve this? Please, take a look at my query below:

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");

Usually this needs to be done via the application level however in the same query you can use insert into .. select from

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

I don't know if this syntax is legal with your DB, but try something like this

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

You can do this with insert select statement:

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

http://sqlfiddle.com/#!9/c574d/1

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM