Sort by value with ORDER BY?

To find out, can you use MySQL in this way to sort?

ORDER BY CompanyID = XXX DESC

What I'm trying to do is use one SQL query to sort everything where X = Y, in this case where CompanyID = XXX. All values ​​in which CompanyID are not XXX should appear after all results in which CompanyID = XXX.

I do not want to limit my request, but I want to sort a specific company over other lists.

+3
source share
5 answers

Your request is in order. CompanyID = xxxgives 1 in coincidence, and 0 otherwise. Just add the CompanyID column as the secondary order column.

ORDER BY CompanyID = XXX DESC, CompanyID ASC

, , CompanyID , .

:

ORDER BY CompanyID <> XXX ASC, CompanyID ASC
+5
ORDER BY FIELD(CompanyID, 'google', 'apple', 'microsoft') ASC

Google =
Microsoft =
=

+8

, :

order by case when CompanyID = XXX then 1 else 2 end
+7

,

SELECT CompanyID, IF(CompanyID = XXX, -1, CompanyID) AS sortby
FROM companies
ORDER BY sortby DESC
+2

, CASE . , 0, else return 1. , , .

 order by case when CompanyID = XXX then 0 else 1 end, CompanyName

, , (, , ).

+2

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


All Articles