MySQL获取每个位置的最后结果

时间:2013-07-11 16:37:22

标签: mysql select where greatest-n-per-group

我有3个查询:

SELECT `update`.`id` AS `id`, `update`.`type` AS `type`, `update`.`date` AS `date`, `update`.`like` AS `like`, `update`.`dislike` AS `dislike` FROM `updates` AS `update` WHERE `type` = '1' ORDER BY `date` DESC LIMIT 1

SELECT `update`.`id` AS `id`, `update`.`type` AS `type`, `update`.`date` AS `date`, `update`.`like` AS `like`, `update`.`dislike` AS `dislike` FROM `updates` AS `update` WHERE `type` = '2' ORDER BY `date` DESC LIMIT 1 (1)

SELECT `update`.`id` AS `id`, `update`.`type` AS `type`, `update`.`date` AS `date`, `update`.`like` AS `like`, `update`.`dislike` AS `dislike` FROM `updates` AS `update` WHERE `type` = '3' ORDER BY `date` DESC LIMIT 1 (1)

我需要获得每种类型的最后日期。如何在一个查询中获取它?

谢谢。

2 个答案:

答案 0 :(得分:4)

这必须是#1最常见的mysql问题。

SELECT u.*
FROM update u
JOIN (SELECT type, MAX(date) maxdate
      FROM update
      WHERE type in ('1', '2', '3')
      GROUP BY type) m
ON u.type = m.type AND u.date = m.maxdate

答案 1 :(得分:0)

SELECT u1.id, u1.type, u1.date, u1.like, u1.dislike
from updates u1
inner join
(
   select type, max(date) as mdate
   from updates
   group by type
) u2 on u2.type = u1.type 
     and u2.mdate = u1.date