这是我的表:
ID UserID Client Time(timestamp)
1 25 Acer 2017-09-13 09:09:13
2 21 Lenovo 2017-09-13 12:09:32
3 20 HP 2017-09-13 14:04:26
4 21 Dell 2017-09-13 17:04:23
5 25 Apple 2017-09-13 17:09:46
.
.
.
我希望首先按时间戳排序结果,获取前5条记录,然后按照用户ID排序
ID UserID Client Time(timestamp)
5 25 Apple 2017-09-13 17:09:46
1 25 Acer 2017-09-13 09:09:13
4 21 Dell 2017-09-13 17:04:23
2 21 Lenovo 2017-09-13 12:09:32
3 20 HP 2017-09-13 14:04:26
我试过这个查询
select * from table order by time Desc, UserID LIMIT 5;
但它似乎没有用,相反我得到了这个结果
ID UserID Client Time(timestamp)
5 25 Apple 2017-09-13 17:09:46
4 21 Dell 2017-09-13 17:04:23
3 20 HP 2017-09-13 14:04:26
2 21 Lenovo 2017-09-13 12:09:32
1 25 Acer 2017-09-13 09:09:13
我不确定我哪里出错了。
答案 0 :(得分:3)
您可以尝试这样做:
SELECT * FROM
(
SELECT *
FROM table
ORDER BY time DESC
LIMIT 5
) AS firstusers
ORDER BY UserID
答案 1 :(得分:0)
行。您需要获取按时间戳排序的前5个记录,并按userID重新排序。这是代码:
SELECT * FROM (
SELECT* FROM
table1
ORDER BY time DESC
LIMIT 5) firstfive
ORDER BY UserID DESC
答案 2 :(得分:0)
应改为order by UserID DESC, time Desc
:
select *
from table1 order by UserID DESC, time Desc;
这将为您提供所需的订单:
| ID | UserID | Client | Time |
|----|--------|--------|----------------------|
| 5 | 25 | Apple | 2017-09-13T17:09:46Z |
| 1 | 25 | Acer | 2017-09-13T09:09:13Z |
| 4 | 21 | Dell | 2017-09-13T17:04:23Z |
| 2 | 21 | Lenovo | 2017-09-13T12:09:32Z |
| 3 | 20 | HP | 2017-09-13T14:04:26Z |
答案 3 :(得分:0)
您需要内联视图,首先按time
获取5行,然后UserID
SELECT * FROM
(
SELECT *
FROM table
ORDER BY time DESC
LIMIT 5
)
ORDER BY UserID DESC
因此,上面的查询嵌套了select
,它将首先执行,并按time
降序排列5行。然后,我们将使用此结果集进行外部查询,并按UserID