MySQL, how to sort by category?

I know how to selectsort one category separately and how to selectsort all categories according to ASCor DESC. My question is how to selectcategorize all categories in such a way that, for example, the fifth category comes first and the others come first?

+4
source share
2 answers

Assuming that the fifth category simply means that you want to prefer a certain category, for example Category-Name, you can use CASE:

SELECT t.*
FROM dbo.Tablename t
ORDER BY CASE WHEN t.Category = 'Category-Name' THEN 0 ELSE 1 END ASC,
         Category ASC
+3
source

You can use the function field()

select *
from categories
order by field(id,5) desc,id

or

select *
from categories
order by id= 5 desc,id
+1

Source: https://habr.com/ru/post/1584889/


All Articles