Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Order By date column and integer column, but specify ordering rules of integer column?

I have the following table:

-----------------------------------
  PK       integer          date
-----------------------------------
  1          2             03/01/01
  2          1             04/01/01
  3          3             02/01/01
  4          3             05/01/01
  5          2             01/01/01
  6          1             06/01/01

What I want to do is to order by the date column, BUT have the dates with integer 2 higher up the order than the other integers. My output would be like this.

-----------------------------------
  PK       integer          date
-----------------------------------
  1          2             01/01/01
  5          2             03/01/01      
  3          3             02/01/01
  2          1             04/01/01
  4          3             05/01/01
  6          1             06/01/01

At the moment I'm totally clueless as to how to achieve this in MySQL, or even if its possible. I haven't tried anything yet as I have no idea where to even start.

I should say that the order of integers that aren't 2 is not a concern, so the following table is equally good.

-----------------------------------
  PK       integer          date
-----------------------------------
  1          2             01/01/01
  5          2             03/01/01      
  2          1             04/01/01
  6          1             06/01/01
  3          3             02/01/01
  4          3             05/01/01
like image 394
GWed Avatar asked Feb 10 '14 19:02

GWed


1 Answers

You can order the query by a calculated expression, e.g., case:

SELECT   *
FROM     `my_table`
ORDER BY CASE `integer` WHEN 2 THEN 1 ELSE 0 END DESC, `date` ASC
like image 93
Mureinik Avatar answered Oct 26 '22 23:10

Mureinik