How to make Join with multiple tables?

Asked

Viewed 56 times

0

I have 4 tables they are already with Foreign key.

aluno:
id
matricula
username
curso_id          // referencia a id_cursos da tabela cursos, coluna id_cursos.

cursos: 
id_cursos
nome_cursos

modulos:
id_modulos
nome_modulos
cursos_id         //faz referencia a tabela cursos, coluna id_cursos.

materias:
id_materias
nome_materias
modulos_id       // faz referencia a tabela modulos, coluna id_modulos.

in the student table has 2 record:


id | matricula | username | curso_id.<br>
1  | 12345678  | Usuario1 | 1 

id | matricula | username | curso_id.<br>
2  | 12344321  | Usuario2 | 2 

I want to return all the tables but only the columns that are related to the pupil column curso_id 1, example, a student has a course, a course has several modules, a module has several mateiras, so have to return in this order, selected student takes Administration course, then returns the modules of the Administration course and the materials of the modules.

1 answer

1


There are these two ways:

USING JOIN:

SELECT * FROM ALUNO AS AL JOIN CURSO AS CS ON AL.curso_id = CS.id_cursos JOIN  MODULOS AS MD ON CS.id_cursos = MD.cursos_id JOIN MATERIAIS AS MT ON MT.modulos_id = MD.id_modulos

And using WHERE:

SELECT * FROM ALUNO, CURSOS, MODULOS, MATERIAIS WHERE ALUNO.curso_id =  CURSOS.id_cursos AND MODULOS.cursos_id = CURSOS.id_cursos AND MATERIAIS.modulos_id = MODULOS.id_modulos

Browser other questions tagged

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