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.
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.
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
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
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.