SQL Max()问题

时间:2009-09-09 01:39:24

标签: sqlite

现在我正在这样做:

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

我仍然收到修订号较低的邮件。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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;