从不同的查询中加入两个SQL表

时间:2018-05-25 00:50:31

标签: mysql sql

我正在尝试加入这两个查询。有人可以帮忙吗?

查询1 -

SELECT provas.id, disciplinas.disciplina, disciplinas.grupo,salas.sala 
FROM provas, disciplinas, horarios, salas 
WHERE provas.id = provas.id AND provas.id_disciplina = disciplinas.id AND provas.id_horario = horarios.id AND provas.id_sala = salas.id AND provas.id_horario JOIN horarios ON ;

查询2 -

SELECT dias.dia, meses.nome, horas.hora, minutos.minuto 
FROM horarios, meses, dias, horas, minutos 
WHERE horarios.id = horarios.id AND horarios.id_dia = dias.id AND horarios.id_hora = horas.id AND horarios.id_mes = meses.id AND horarios.id_minuto = minutos.id;

Main table

Second Main table

我想将“provas”表与“horario”相关联,但是horario表有更多的外键

provas =考试 horarios = scheudule

我想在考试表上加入shedule,但是sheudule有更多的外键用于表“天”,“月”,“小时”和“分钟”

All involved tables

2 个答案:

答案 0 :(得分:0)

您可以尝试以下查询。我没有运行它来确保没有语法错误。但你可以看到这个概念。您可以使用第二个查询的结果集加入,如下所示。我建议你再次考虑原始查询中的连接。您可以在我的答案中更改连接,因为它适合您的目的。

SELECT ps.id, das.disciplina, das.grupo,s.sala 
FROM provas ps 
inner join disciplinas das on ps.id_disciplina = das.id
inner join horarios hs on ps.id_horario = hs.id
inner join salas s on ps.id_sala = s.id
inner join (
SELECT d.dia, ms.nome, h.hora, m.minuto, hs.id hsid
FROM horarios hs
inner join  meses ms on hs.id_mes = ms.id
inner join dias d on hs.id_dia = d.id
inner join horas h on hs.id_hora = h.id 
inner join minutos m on hs.id_minuto = m.id) zz on ps.id_horario = zz.hsid

答案 1 :(得分:0)

我的解决方案(我更喜欢这种方式):

 SELECT provas.id, disciplinas.disciplina, disciplinas.grupo,salas.sala ,dias.dia, meses.nome, horas.hora, minutos.minuto 
 FROM provas, disciplinas, horarios, salas, meses, dias, horas, minutos
 WHERE provas.id = provas.id AND provas.id_disciplina = disciplinas.id AND provas.id_horario = horarios.id AND provas.id_sala = salas.id AND provas.id_horario AND horarios.id_dia = dias.id AND horarios.id_hora = horas.id AND horarios.id_mes = meses.id AND horarios.id_minuto = minutos.id;