MYSQL order by text

╄→гoц情女王★ 提交于 2020-07-19 04:25:29

问题


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?


回答1:


Do simple as-

ORDER BY FIELD(Status, 'Unanswered', 'Answered', 'Done')



回答2:


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')


来源:https://stackoverflow.com/questions/32923591/mysql-order-by-text

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!