How to select in 3 tables?

Asked

Viewed 11,049 times

6

I need to do SELECT in two tables with relationship n for n, soon, I will have to make use of the intermediate table as well, but I don’t know how to do it. I am using PHP and Sqlserver database.

  • If you do not state which tables and which data from these tables, it is difficult to help.

  • 2

    Use the join and the taste(inner, right etc) suitable for the expected results.

4 answers

6

You need to list all 3 tables using the JOIN command See 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 represents the Use of joins.

inserir a descrição da imagem aqui

  • More detailed than this could not :)

3

You need to make use of JOIN in your consultation.

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

2

1

Let’s take an example:

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

In this example I want to pick up 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 could just make the call you make in PHP by calling this SQL.

Browser other questions tagged

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