在SQL查询中查找最后一条记录

时间:2013-12-02 23:37:49

标签: mysql sql

这实际上是Massive SQL查询的一部分,但我有这个代码工作,现在我似乎无法弄清楚为什么它找不到最后一个约会记录。

我要做的是将所有其他约会加入到自己中,找出哪一个是最后一个。我的所有结果似乎都是空的。但这不正确,因为我的数据肯定有约会。所以我认为我的选择查询有问题。任何帮助都会很棒。

SELECT `animal_id`, 
       FROM_UNIXTIME(`lastappointment`.`appointmentdata_starttime`,'%D %M %Y') AS 'Last Appointment'
FROM `animal`
LEFT JOIN (
    SELECT `lAppointment`.*
    FROM `appointment` AS `lAppointment`
    LEFT JOIN `appointment` AS `nlAppointment` 
       ON `nlAppointment`.`appointmentdata_starttime` <= NOW()
           AND `nlAppointment`.`appointmentdata_starttime` > `lAppointment`.`appointmentdata_starttime`
           AND `nlAppointment`.`appointmentdata_animal` = `lAppointment`.`appointmentdata_animal`
    WHERE `lAppointment`.`appointmentdata_starttime` <= NOW() 
       AND `nlAppointment`.`appointment_id` IS NULL
    ) AS `lastappointment` 
    ON `animal_id` = `lastappointment`.`appointmentdata_animal`
WHERE `animaldata_active` IS NOT NULL
GROUP BY animal_id;

1 个答案:

答案 0 :(得分:0)

使用LEFT JOIN获取MAX()是您能想到的最慢的方法。我建议你改变这样的内部查询(使用GROUP BY):

SELECT `animal_id`,
  FROM_UNIXTIME(`lastappointment`.`last_appointment`, '%D %M %Y') AS 'Last Appointment'
FROM `animal`
LEFT JOIN (
  SELECT MAX(appointmentdata_starttime) AS last_appointment,
         appointmentdata_animal
  FROM appointment
  WHERE appointmentdata_starttime <= NOW()
  GROUP BY appointmentdata_animal
  ) AS `lastappointment` 
       ON `animal_id` = `lastappointment`.`appointmentdata_animal`
WHERE `animaldata_active` IS NOT NULL
-- GROUP BY animal_id; --BTW, this group_by is not needed