mysql按时间戳排序最新,并使用限制对该类别的行进行分组

时间:2011-06-22 14:46:40

标签: mysql sql greatest-n-per-group

按时间戳DESC排序,按照Mysql中限制的类别分组

cat  timestamp
----------------
11   1308748405
11   1308747228
13   1308749273
57   1308748289
11   1308746228

...获取格式表,其中按时间戳排序,并且该类别的相关行与限制一起分组。 (即按类别划分所有行,并按时间戳的降序排列组,但保持组合在一起)

cat  timestamp
----------------
13   1308749273
11   1308748405
11   1308747228
57   1308748389

3 个答案:

答案 0 :(得分:0)

我猜你在寻找的是:获取每个类别的最小时间戳,并按时间戳排序结果?

SELECT t.cat, t.timestamp
FROM table t
JOIN (SELECT MIN(timestamp) as min_time, cat
        FROM table
        GROUP BY cat) as tmp
      ON (t.cat = tmp.cat AND t.timestamp = tmp.min_time)
ORDER BY 2 DESC

答案 1 :(得分:0)

SELECT cat, timestamp
FROM yourtable
ORDER BY timestamp DESC
GROUP BY cat
LIMIT 4

没有更多细节,这是你最好的。

答案 2 :(得分:0)

如果你想根据它的最新时间戳排序得到4组。这可能有效:

SELECT tblTes.cat, tblTes.timestamp 
FROM tblTes INNER JOIN (SELECT cat, MAX(TIMESTAMP) AS latest FROM tblTes GROUP BY cat) AS subQuery 
ON tblTes.cat = subQuery.cat AND tblTes.timestamp = subQuery.latest 
ORDER BY tblTes.timestamp DESC LIMIT 4;