Inserting Id of a Foreign Key into a Relational Database

Asked

Viewed 44 times

0

Good morning.

I am beginner in Database and programming and have a question, which query to recover the id to insert in a table with foreign key?

I am using the MYSQL database.

Example, I have the table "posting", in the table post have the fields " idPostagem", "Title", "Content" and "Idcategory" (Foreign key)

And in the table "Category" has the fields "Idcategory" and "Name".

Let’s assume that the post panel appears to fill in the name, title, content and a combobox with the list of Categories.

In insertion it would be so "

INSERT INTO postagem (titulo, conteudo, idCategoria)
VALUES ('Titulo', 'Conteudo', idCategoria);

Let’s assume that the user selected the category "Police", as I do to recover the ID of this category from the Category table and insert the ID in the table "Post"

I’m sorry if the question was simple or silly, but I’m starting now and I’m stalling on this part.

Thank you all!

  • you could create a sub-query to return the id of the desired category or when you show on the screen to the user which category you also bring the id of the category, and when you give the Insert you can redeem these values! You are using which back-end language?

1 answer

2


Assuming your Category table name is unique:

INSERT INTO postagem (idPostagem, titulo, conteudo, idCategoria)
VALUES (<Seu idPostagem>, 'Titulo', 'Conteudo', 
(select idCategoria from Categoria where nome = 'Policial'));

If your name might not be unique, you need to pass the id coming from the screen. But this subquery solves the problem well if its return is no more than 1 value.

  • If the database is Postgresql, it will be the same query or has difference?

  • @Felipepachecopaulucio I don’t know very well the postgree, but I don’t believe in any particularity.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.