简体   繁体   中英

Insert foreign key into table

I have two tables.

basically i want to insert an id and a string into a table

However, id is a foreign key to another table in which customerId is the primary key

Furthermore my parent table has name

What i have, is name and the string that i get from a web ui. However, since i dont have the id that match the customerid of name in the parent table, i don't know how to insert it.

i got this so far, which by the way is my silly attempt to work my human logic around this issue:

INSERT INTO `PostDb`(`Offer`)
VALUES ("String") AND PostDb.id
WHERE CustomerDb.id = PostDb.id AND CustomerDb.name = "MyNameThatIHave"

What would work though. is that i do the following:

SELECT PostDb.id
FROM `PostDb` JOIN CustomerDb
WHERE `CustomerId` = CustomerDb.id AND CustomerDb.name = "MyNameThatIHave"

And then use the id that i get in a new insert command like this:

INSERT INTO `PostDb`(`CustomerId`, `Offer`) 
VALUES ("THE ID I GOT BEFORE","STRING")

Basically i want to achieve in ONE query, what the two before stated queries does

Have you tried LAST_INSERT_ID() function which gives you the last inserted ID PK provided that ID is an auto_increment column.

Once you get that, then you can insert in your child table in your FK column along with the rest attributes.

In that case, use a INSERT INTO .. SELECT FROM construct like

INSERT INTO `PostDb`(`CustomerId`, `Offer`) 
SELECT PostDb.`CustomerId`, 'Some Value'
FROM `PostDb` JOIN CustomerDb
ON `PostDb`.`CustomerId` = CustomerDb.id 
WHERE CustomerDb.name = "MyNameThatIHave";

You can use SELECT to get values for insert:

INSERT INTO `PostDb`(`Offer`, customerid)
  SELECT 'Whatever', id FROM customerdb
    WHERE name = 'MyNameThatIHave'

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