3

okay so I know how I can sort by id or number like

$getTicket = $sql->query("SELECT * FROM `ticket` 
                          WHERE `user`='$user->name' 
                          ORDER BY `id` DESC");

I have Status in the ticket table, and in that I have 3 things:

1) Answered 2) Unanswered 3) Done

I want to sort it in this way:

1) Unanswered
2) Answered
3) Done

is there a way to do this?

Funk Forty Niner
  • 74,372
  • 15
  • 66
  • 132
Patric Nøis
  • 198
  • 2
  • 7
  • 27
  • dupe of [Ordering by specific field value first](https://stackoverflow.com/questions/14104055/ordering-by-specific-field-value-first) – underscore_d Jul 07 '20 at 15:35

2 Answers2

6

Do simple as-

ORDER BY FIELD(Status, 'Unanswered', 'Answered', 'Done')
Gordon Linoff
  • 1,198,228
  • 53
  • 572
  • 709
Rohit Kumar
  • 1,899
  • 1
  • 9
  • 16
4

You can generally use case

SELECT * FROM `ticket` 
WHERE `user` = '$user->name' 
ORDER BY case when Status = 'Unanswered' then 1
              when Status = 'Answered' then 2
              else 3
         end

or MySQL specific find_in_set

SELECT * FROM `ticket` 
WHERE `user` = '$user->name' 
ORDER BY find_in_set(Status, 'Unanswered,Answered,Done')
juergen d
  • 195,137
  • 36
  • 275
  • 343