2009-09-09 57 views
2

現在我這樣做:SQL MAX()問題

SELECT * FROM messages WHERE location_id = 7 AND date(date) <= date('now', 'localtime') ORDER BY date,revision LIMIT 1 

這給了我最近的消息,最高版本#。

如何檢索所有最新的消息?如果我這樣做:

SELECT * FROM messages WHERE date(date) <= date('now', 'localtime') ORDER BY date,revision 

我仍然收到修訂號較低的消息。

回答

0

下面是每個位置找到的最新版本的查詢:

SELECT m1.* FROM messages m1 
LEFT OUTER JOIN messages m2 
    ON (m1.location_id = m2.location_id AND m1.revision < m2.revision) 
WHERE m2.location_id IS NULL 
ORDER BY date, revision; 
+0

嘿比爾, 實際上,我試圖找到最近的評論(即最高的版本號,最近日期)per location_id – tuzzolotron 2009-09-09 04:05:27

+0

我編輯了我的答案。 – 2009-09-09 04:37:43

1
SELECT * FROM messages m1 
WHERE date(date) <= date('now', 'localtime') 
    and revision = (select max(revision) from messages m2 where date(m2.date) = date(m1.date)) 
    and location_id = 7 
ORDER BY date,revision