[英]Order by one column and then by another
This is my table: 这是我的表:
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
.
.
.
I want the result to be ordered by timestamp first, fetching the first 5 records, and then ordering by user id like this 我希望结果首先按时间戳排序,获取前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
i tried this query 我试过这个查询
select * from table order by time Desc, UserID LIMIT 5;
but it doesn't seem to work, instead i get this as the result 但它似乎没有用,相反我得到了这个结果
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
I am not sure where i am going wrong. 我不知道我哪里出错了。
You can try to do this: 您可以尝试这样做:
SELECT * FROM
(
SELECT *
FROM table
ORDER BY time DESC
LIMIT 5
) AS firstusers
ORDER BY UserID
OK. 好。 You need to fetch the first 5 records ordered by timestamp, and reorder them by userID.
您需要获取按时间戳排序的前5个记录,并按userID重新排序。 Here is the code:
这是代码:
SELECT * FROM (
SELECT* FROM
table1
ORDER BY time DESC
LIMIT 5) firstfive
ORDER BY UserID DESC
It should be order by UserID DESC, time Desc
instead: 它应该是
order by UserID DESC, time Desc
而不是order by UserID DESC, time Desc
:
select *
from table1 order by UserID DESC, time Desc;
This will give you the same order you are looking for: 这将为您提供所需的订单:
| 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 |
You need in-line view, where first get the 5 rows order by time
and then UserID
您需要内联视图,首先按
time
顺序获取5行,然后是UserID
SELECT * FROM
(
SELECT *
FROM table
ORDER BY time DESC
LIMIT 5
)
ORDER BY UserID DESC
So, above query has nested select
which will execute first and get you 5 rows ordered descending by time
. 因此,上面的查询具有嵌套
select
,它将首先执行,并按time
降序排列5行。 Then, we will use this resultset to outer query and order the row by UserID 然后,我们将使用此结果集进行外部查询,并按UserID对行进行排序
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.