For clarification, are you able to use MySQL this way to sort?
ORDER BY Comp开发者_Python百科anyID = XXX DESC
What I am trying to do is use one sql query to sort everything where X = Y, in this case, where CompanyID = XXX. All values where CompanyID is not XXX should come after all the results where CompanyID = XXX.
I don't want to limit my query but I do want to sort a particular company above other listings.
ORDER BY FIELD(CompanyID, 'google', 'apple', 'microsoft') ASC
Google = first
Microsoft = third
The rest = last
You can use a case in an order by, like:
order by case when CompanyID = XXX then 1 else 2 end
Your query is fine. CompanyID = xxx
yields 1 on a match, and 0 otherwise. Just add the CompanyID column as the secondary order column.
ORDER BY CompanyID = XXX DESC, CompanyID ASC
This way, you get records where the CompanyID matches your constant first, then the rest are in order.
Alternatively, you could do this:
ORDER BY CompanyID <> XXX ASC, CompanyID ASC
You might want to try using a CASE statement in your order by expression. When the company id matches your preferred company, return 0, else return 1. Then order by company name like usual in a secondary order by column.
order by case when CompanyID = XXX then 0 else 1 end, CompanyName
That way you have your preferred company at the top, then all of the rest order alphabetically by name (or however you want it ordered).
You could probably fake it out
SELECT CompanyID, IF(CompanyID = XXX, -1, CompanyID) AS sortby
FROM companies
ORDER BY sortby DESC
精彩评论