[英]SQL - Select x most recent rows with common column value
Example 例
I would like to select the 5 most recent rows that have the same group value from the following table. 我想从下表中选择5个具有相同组值的最新行。
--------------------------------------------
| id | group | timestamp |
--------------------------------------------
| 1 | circle | 1468287300 |
| 2 | square | 1468287816 |
| 3 | square | 1468287694 |
| 4 | circle | 1468287252 |
| 5 | circle | 1468287987 |
| 6 | circle | 1468287068 |
| 7 | square | 1468287149 |
| 8 | circle | 1468287422 |
--------------------------------------------
我认为这应该可行,请检查并告知我
SELECT * FROM Table1 GROUP BY group ORDER BY timestamp DESC LIMIT 5;
Try this: 尝试这个:
SELECT t.`id`, t.`group`, t.`timestamp`
FROM (
SELECT
t1.*,
IF(@grp = `group`, @rowno := @rowno + 1, @rowno := 1) AS rowno,
@grp := `group`
FROM (
SELECT *
FROM yourtable
ORDER BY `group`, `timestamp` DESC
) t1
CROSS JOIN (SELECT @grp := null, @rowno := 0) t2
) t
WHERE rowno < 6
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.