Skip to content
Advertisement

How do I insert data into a table where one of the values should be a foreign key from another table?

I wanted to update the post table (main table) with those data:

However, the post table userid column only accepts an integer (foreign keys from the user table (userid)), not username string itself.

How can I do this with INSERT, SELECT/WHERE query?

There are the tables.

post

user

Here is what it should look like after the insertion:

post

Advertisement

Answer

Assuming postid auto-increments:

Note that this will not insert anything if the given username is not found.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement