Inserting a Foreign Key Id into a Relational Database

0

Good morning.

I am a beginner in Database and programming and I have a question, what is the query to retrieve the id to insert into a foreign key table?

I'm using the MYSQL database.

Example, I have the "post" table, the post table has the fields "idPost", "Title", "Content" and "CategoryID"

And the "Category" table has the "CategoryID" and "Name" fields.

Let's assume that in the posting panel it appears to populate the name, title, content, and a combobox with the Categories list.

The insertion would look like this "

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

Let's assume that the user has selected the "Policeman" category, how do I retrieve the ID of this category from the Category table and insert the ID in the "Post" table

Sorry if the question was simple or silly, but I'm starting now and I screwed up in that part.

Thank you all!

    
asked by anonymous 10.12.2018 / 13:25

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 may not be unique, you need to pass the id from the screen. But this subquery solves the problem well if its return is no more than 1 value.

    
10.12.2018 / 13:37