2013-07-11 48 views
0

我有3个疑问:的MySQL获得每个最后的结果,其中

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) 

我需要为每种类型的最后日期。我怎样才能在一个查询中得到它?

谢谢。

回答

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 
+0

此查询可能返回多于三行。如果没有'(type,date)'是唯一的保证,这个查询可以为特定类型返回多行。 – spencer7593

+0

@ spencer7593由于该问题未指定在可能具有相同日期的行之间进行选择的条件,因此我认为它们是唯一的。可以将GROUP BY类型“date”添加到查询中以删除重复项,但其他列可以从不同的行中随机选择。 – Barmar

+0

@Barmar谢谢。超。我使用Kohana ORM,我不能在JOIN中使用构造。它可以更简单吗?我使外部建设更简单,但不能和内部一样做。 :( –

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 
相关问题