How to do select in 3 tables?

6

I need to do SELECT on two tables with relationship n to n , so I will have to make use of the middle table too, but I do not know how to do this. I'm using PHP and SQLServer database.

    
asked by anonymous 23.11.2015 / 17:07

4 answers

5

You need to relate the 3 tables through the JOIN command Here's a simple example.

SELECT * FROM tabelaA a
INNER JOIN tabelaRelacao r on a.id_tabelaA = r.id_tabelaA
INNER JOIN tabelaB b on a.id_tabelaB = r.id_tabelaB

Follows an image that graphically displays the% use of%.

    
23.11.2015 / 17:13
3

You need to make use of JOIN in your query.

SELECT
    T.ID_Tabela1,
    T.Descricao,
    T3.Descricao
FROM Tabela1 T
INNER JOIN
    Tabela2 T2 ON T2.ID_Tabela2 = T.ID_Tabela2
INNER JOIN
    Tabela3 T3 ON T3.ID_Tabela3 = T2.ID_Tabela3
    
23.11.2015 / 17:13
2

Use joins:

Inner Join: Required registration in A and B Left Join: Required registration in A, B can be null Right Join: Required registration in B, A can be null

Tutorial: link

SELECT
    t1.nome, t1.id01, t2.id01, t2.id02, t3.curso, t3.id02
FROM
    TABELA01 t1
    INNER JOIN TABELA02 t2
    ON t1.id01 = t2.id01
    INNER JOIN TABELA 03 t3
    ON t2.id02 = t3.id02
    
23.11.2015 / 17:16
1

Let's give an example:

You have an Article object that has more than one category, and a category can have more than one article.

In this example I want to get 10 articles with all categories.

SELECT * FROM artigo

LEFT JOIN artigo_categorias ON (artigo.id = artigo_categorias.artigo_id)
LEFT JOIN categorias ON (artigo_categorias.categoria_id = categoria_id)

LIMIT 10

In this case, you just need to make the call you make in PHP by calling this SQL.

    
23.11.2015 / 17:12