2013-07-11 75 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 
相關問題