Select data from two tables

1

I'm having trouble relating data from two tables.

I have two tables. Table Posts and the Favorites table.

Tabela Favoritos:
id, id_utilizador, id_post
1   109            20 
2   200            20
3   105            104   
4   109            150
-------------------------------------------
Tabela Posts:
id, id_post, id_owner, titulo, discricao
1   20       123            qqcoisa  qqcoisa
2   150      321            xxxxx    xxxxx   


--------------------------------------------

I wanted to put user bookmarks id = 109, including the title and description of the posts table on a page?

utilizador post titulo descricao
109        20   qqcoisa qqcoisa
109        150  xxxxxx  xxxxx
    
asked by anonymous 21.08.2015 / 14:08

4 answers

3

I think what you want to do is an INNER JOIN:

SELECT Favoritos.id_utilizador, Posts.id_post, Posts.titulo, Posts.descricao 
FROM Favoritos 
INNER JOIN Posts ON Favoritos.id_utilizador=Posts.id_utilizador;

No SELECT places the fields you want to get, not forgetting the name of the table to which the field belongs.

No FROM puts the names of the tables you want to join and the way they are to be joined ( INNER JOIN , OUTER JOIN , LEFT JOIN or RIGHT JOIN ). Then you tell them where they are going to be together, that is, the element in common in both tables.

You can still add a WHERE to put conditions, and as in SELECT you have to put the table name and the field name (Ex: Posts.id_post = 20).

    
21.08.2015 / 14:17
2

You need to use a INNER JOIN , which selects columns from two tables according to a condition that relates data from the two tables:

link

    
21.08.2015 / 14:18
2

Basically that would be it.

Using PDO:

$buscar = $suaConexao->prepare("SELECT * FROM posts LEFT JOIN favoritos ON posts.id = favoritos.id_utilizador");
//Nessa query sera buscado tudo na tabela posts que tenham um ID igual a um id_utilizador da tabela favoritos

$buscar->execute(); // Executa a busca
$linha = $buscar->fetchAll(PDO::FETCH_ASSOC); // Retorna o resultado como array associativo
foreach($linha $resultado): // Inicia o loop para pegar todos os dados
echo $resultado['id_owner'];
echo $resultado['titulo'];
echo $resultado['descricao'];
    
21.08.2015 / 14:14
0

Use INNER JOIN, if you want to bring all the fields of the other table you are using, use LEFT JOIN.

    
22.08.2015 / 17:47