Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Order by multiple column combined (not order by field1 asc, field2 asc)

it seems like a typical question but it's different.

I have a table with an id and 3 timestamp fields (to simply). Initially all 3 fields are null, and they get filled with values. Examples of rows are:

id time1      time2      time3
1  1259625661 1259643563 null
2   null      1259621231 null
3  1259625889 null       1259644511
4   null      1259621231 null
5   null      null       1259644511
6   null      1259621231 null
7  1259625889 null       null

What I need is to get a list of the id's sorted by the most recent timestamp (ignoring if it's in time1, time2 or time3). Doing a order by time1 desc, time2 desc, time3 desc gives me a wrong list, as it first sorts all the time1 field, then the second, etc...

Expected result is a list of id's.

That can be done in MySQL in a single query? Thanks

like image 917
Ferran Gil Avatar asked Dec 01 '09 15:12

Ferran Gil


People also ask

How do I sort multiple columns in MySQL?

Summary. Use the ORDER BY clause to sort the result set by one or more columns. Use the ASC option to sort the result set in ascending order and the DESC option to sort the result set in descending order. The ORDER BY clause is evaluated after the FROM and SELECT clauses.

Can we use ORDER BY on two columns in MySQL?

Using ORDER BY to sort on two columns In such a case, MySQL treats the first field as primary and the latter as secondary. Therefore, it first sorts the primary and then the second one. Hence, in this example, we'll demonstrate ORDER BY on two columns, one field as ASC, and another DESC.

Can we have 2 ORDER BY in MySQL?

Using with multiple columnsDefine your multiple column names in ORDER BY clause separated by a comma (,). You can also specify your sorting order ASC or DESC . In the above query, I am ordering the emp_salary table by age in Ascending order and salary by descending order.

How do I create a secondary sort in MySQL?

When sorting your result set using the SQL ORDER BY clause, you can use the ASC and DESC attributes in a single SELECT statement. This example would return the records sorted by the category_id field in descending order, with a secondary sort by product_name in ascending order.


1 Answers

SELECT  *
FROM    mytable
ORDER BY
        GREATEST(
        COALESCE(time1, 0),
        COALESCE(time2, 0),
        COALESCE(time3, 0)
        ) DESC
like image 173
Quassnoi Avatar answered Oct 06 '22 00:10

Quassnoi