MySQL Query: Prioritize Specific Items, Then Sort the Rest
This MySQL query prioritizes specific items in your results, displaying them first, followed by the remaining items sorted according to a chosen order.
Here's how to construct the query:
<code class="language-sql">SELECT id, name FROM friends ORDER BY CASE WHEN name = 'SpecificItemName' THEN 0 -- Prioritize 'SpecificItemName' ELSE 1 -- All other items END, name ASC; -- Sort the remaining items alphabetically by name (adjust as needed)</code>
Replace 'SpecificItemName'
with the actual name of the item you want to prioritize. The CASE
statement assigns a value of 0 to the prioritized item and 1 to all others. The ORDER BY
clause then sorts based on this value, placing the prioritized item first. The name ASC
clause (or any other sorting criteria) sorts the remaining items alphabetically by name. You can change ASC
to DESC
for descending order, or replace name
with another column for different sorting. This approach ensures that your specific item always appears at the top of the results, with the rest of the data organized as you specify.
The above is the detailed content of How to Prioritize a Specific Item in MySQL Queries Then Sort the Rest?. For more information, please follow other related articles on the PHP Chinese website!