Mysql SELECT searching for value in another table

Asked

Viewed 16,948 times

4

I have 2 tables:

paginas and paginas_categorias

On the table paginas I have a column called id_categoria, which would be the corresponding id of the table paginas_categorias. Using this id, I wanted to return the column nome table paginas_categorias.

I will try to give another example: my goal is that in this query:

SELECT id_paginas FROM paginas

return the value nome table paginas_categorias:

SELECT nome FROM paginas_categorias WHERE id = (id informado na outra tabela) 

I saw that this would be a subquery, but I couldn’t use the examples with my reality.

  • 1

    You need to use a Join to merge tables.

3 answers

4


Making the join you will have the list of all names of the table pages_categories that appear in the table pages.

SELECT paginas_categorias.nome 
FROM paginas INNER JOIN paginas_categorias 
ON (paginas.i_categoria = paginas_categorias.id);

2

If I understand, it’s more or less like this...

SELECT nome FROM paginas_categorias 
INNER JOIN paginas 
ON (paginas_categorias.id = paginas.id_categorias)

2

With the answers I searched and understood how JOIN works between the tables and managed to return the values as I wanted, follows:

SELECT paginas.id, paginas.nome_pagina, paginas_categorias.nome AS nome_categoria, paginas.id_pagina_curtir, paginas.youtube FROM paginas INNER JOIN paginas_categorias ON paginas.id_categoria = paginas_categorias.id WHERE paginas.id_facebook = xxx

Browser other questions tagged

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