Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order by one column and then by another

Tags:

mysql

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

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.

like image 931
Harsha Jasti Avatar asked Oct 20 '25 04:10

Harsha Jasti


2 Answers

It should be order by UserID DESC, time Desc instead:

select * 
from table1 order by  UserID DESC, time Desc;

demo

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 can try to do this:

SELECT * FROM
(
    SELECT *
    FROM table
    ORDER BY time DESC
    LIMIT 5
) AS firstusers
ORDER BY UserID
like image 33
Iurii Drozdov Avatar answered Oct 21 '25 20:10

Iurii Drozdov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!