在选择MYSQL之后进行连接

时间:2013-08-22 17:16:45

标签: mysql select

我想知道在选择或查询后是否可以进行连接。这是起始查询:

    SELECT * 
      FROM citas 
INNER JOIN cita_solicituds 
        ON citas.id=cita_solicituds.cita_id 
INNER JOIN users 
        ON citas.user_id = users.id

正如您所看到的,我正在进行两次连接,基表为citas,并且可以加入cita_solicituds和用户。这是完美地检索结果。但是,在我得到这个结果后,我想做另一个连接但是有一个与citas无关的表。它有点像:

   (SELECT * 
      FROM citas 
INNER JOIN cita_solicituds 
        ON citas.id=cita_solicituds.cita_id 
INNER JOIN users 
        ON citas.user_id = users.id) 
INNER JOIN horario 
        ON (RESULT JUST FETCHED).horario_id = horario.id

3 个答案:

答案 0 :(得分:2)

试试这个:

SELECT *
FROM
  (SELECT * 
  FROM citas 
  INNER JOIN cita_solicituds ON citas.id=cita_solicituds.cita_id 
  INNER JOIN users ON citas.user_id = users.id) q 
INNER JOIN horario ON q.horario_id = horario.id

我认为您在horario_idcitascita_solicituds中有一个字段users

答案 1 :(得分:0)

可以是:

SELECT * FROM
  (SELECT * 
  FROM citas 
  INNER JOIN cita_solicituds ON citas.id=cita_solicituds.cita_id 
  INNER JOIN users ON citas.user_id = users.id) q, horario h
where q.horario_id = h.horario.id

答案 2 :(得分:0)

连接几个表没有问题,你不需要对它们进行分组,MySQL会理解最佳的顺序:

SELECT * 
FROM citas 
INNER JOIN cita_solicituds 
  ON citas.id=cita_solicituds.cita_id 
INNER JOIN users 
  ON citas.user_id = users.id
INNER JOIN horario
  -- not sure if horario_id comes from users or cita_solicituds 
  ON users.horario_id = horario.id