我有3张桌子,我想加入它。
检查这个小提琴:http://sqlfiddle.com/#!2/20410/2
在列中:segunda,terca,quarta,quinta和sexta 而不是数字...我需要“materias”表中的名称。 但我检查了同一个表中的所有ID“materias”
这可能吗?有人可以帮帮我吗?
答案 0 :(得分:1)
尝试以下查询:
SELECT
h.id_classe,
h.id_aula,
s.serie,
m1.materia as segunda,
m2.materia as terca,
m3.materia as quarta,
m4.materia as quinta,
m5.materia as sexta
FROM horario_de_aulas h
INNER JOIN materias as m1 on h.segunda = m1.id_materia
INNER JOIN materias as m2 on h.terca = m2.id_materia
INNER JOIN materias as m3 on h.quarta = m3.id_materia
INNER JOIN materias as m4 on h.quinta = m4.id_materia
INNER JOIN materias as m5 on h.sexta = m5.id_materia
INNER JOIN series s ON h.classe = s.id_serie = 1
LIMIT 4
答案 1 :(得分:1)
您可以使用内部联接和使用子查询以两种方式执行此操作。
使用内部联接:
SELECT
h.id_classe,
h.id_aula,
s.serie,
m1.materia as segunda,
m2.materia as terca,
m3.materia as quarta,
m4.materia as quinta,
m5.materia as sexta
FROM horario_de_aulas h
INNER JOIN materias as m1 on h.segunda = m1.id_materia
INNER JOIN materias as m2 on h.terca = m2.id_materia
INNER JOIN materias as m3 on h.quarta = m3.id_materia
INNER JOIN materias as m4 on h.quinta = m4.id_materia
INNER JOIN materias as m5 on h.sexta = m5.id_materia
INNER JOIN series s ON h.classe = s.id_serie = 1
LIMIT 4
使用子查询
SELECT
h.id_classe,
h.id_aula,
s.serie,
(select materia from materias where id_materia=h.segunda) as segunda,
(select materia from materias where id_materia=h.terca) as terca,
(select materia from materias where id_materia=h.quarta) as quarta,
(select materia from materias where id_materia=h.quinta) as quinta,
(select materia from materias where id_materia=h.sexta) as sexta
FROM horario_de_aulas h
INNER JOIN materias m
INNER JOIN series s ON h.classe = s.id_serie = 1
LIMIT 4