LEFT JOIN只是多对一的最新一行

时间:2016-06-03 13:54:20

标签: mysql

一直撞到墙上,无法解决这个问题:\

SELECT
  `people`.*,
  `students`.*,
  `student_class_relationships`.*,
  `geo_checkin_on_campus`.`datetime_created` as checkin_time
FROM `student_class_relationships`
  LEFT OUTER JOIN `students`
    ON `student_class_relationships`.`student` = `students`.`id`
  LEFT OUTER JOIN `people`
    ON `students`.`student` = `people`.`id`
  LEFT OUTER JOIN `geo_checkin_on_campus`
    ON `students`.`id` = (
      SELECT MIN(`geo_checkin_on_campus`.`student`)
      FROM `geo_checkin_on_campus`
      WHERE `geo_checkin_on_campus`.`student` = `students`.`id`
    )
 WHERE `class` = 56

预期结果是许多行,每个students.id只有一个条目。

这是我的schema

3 个答案:

答案 0 :(得分:2)

从性能角度来看,这不是最好的查询,

但只是为了解决您的问题,这是我的尝试:

SELECT
  `people`.*,
  `students`.*,
  `student_class_relationships`.*,
  geoCheckinOnCampus.datetimeCreated as checkin_time
FROM `student_class_relationships`
  LEFT JOIN `students`
    ON `student_class_relationships`.`student` = `students`.`id`
  LEFT JOIN `people`
    ON `students`.`student` = `people`.`id`
  LEFT JOIN 
    (
      SELECT 
        student,
        MAX(datetime_created) datetimeCreated
      FROM `geo_checkin_on_campus`
      GROUP BY `student`
    ) geoCheckinOnCampus
  ON `students`.`id` = geoCheckinOnCampus.`student`
 WHERE `class` = 56

注意根据@xQbert的回答,如果您正在寻找最新的日期时间,我会将MIN更改为MAX函数。

答案 1 :(得分:1)

如果我假设你想要go_checkin_on_Campus中每个学生的最新签到(而不是最早创建的日期)那么......

SELECT
  `people`.*,
  `students`.*,
  `student_class_relationships`.*,
  B.`datetime_Updated` as checkin_time
FROM `student_class_relationships`
  LEFT OUTER JOIN `students`
    ON `student_class_relationships`.`student` = `students`.`id`
  LEFT OUTER JOIN `people`
    ON `students`.`student` = `people`.`id`
  LEFT OUTER JOIN (
      SELECT max(datetime_updated), student
      FROM `geo_checkin_on_campus`
      group by student
) B
    ON `students`.`id` = B.Student
 WHERE `class` = 56

答案 2 :(得分:0)

注意:这是一个可能的答案。我将根据OP的评论编辑/修改它。

这基本上什么也没做。这和加入学生ID一样好

LEFT OUTER JOIN `geo_checkin_on_campus`
    ON `students`.`id` = (
      SELECT MIN(`geo_checkin_on_campus`.`student`)
      FROM `geo_checkin_on_campus`
      WHERE `geo_checkin_on_campus`.`student` = `students`.`id`
    )

如果您希望min(或最早)datetime_created使用类似

的内容
LEFT OUTER JOIN (
      SELECT `geo_checkin_on_campus`.`student` student,
              MIN(`geo_checkin_on_campus`.`datetime_created`) dt
      FROM   `geo_checkin_on_campus`
      WHERE  `geo_checkin_on_campus`.`student` = `students`.`id`
      GROUP BY `geo_checkin_on_campus`.`student`
    ) t
    ON `students`.`id` = t.student