I have a MySQL table with the following data (simplified):
INSERT INTO `stores` (`storeId`, `name`, `country`) VALUES
(1, 'Foo', 'us'),
(2, 'Bar', 'jp'),
(3, 'Baz', 'us'),
(4, 'Foo2', 'se'),
(5, 'Baz2', 'jp'),
(6, 'Bar3', 'jp');
Now, I want to be able to get a paginated list of stores that begins with the customers country.
For example, an american customer would see the following list:
Foo
Baz
Bar
Foo2
Baz2
Bar3
The naive solution I'm using right now (example with an american customer and page size 3):
(SELECT * FROM stores WHERE country = "us") UNION (SELECT * FROM stores WHERE country != "us") LIMIT 0,3
Are there any better ways of doing this? Could ORDER BY
be used and told to put a certain value at the top?
To use a Top 10 AutoFilter in Excel, click the AutoFilter drop-down arrow button next to the column heading for the field by which to filter the table. Next, roll down to the “Number Filters” choice. Then select the “Top 10…” option from the side menu that appears to open the “Top 10 AutoFilter” dialog box.
Sort a Selection of RowsHighlight the rows by holding down the Shift key and clicking on the row numbers you want to sort. Right-click on the selected area and select Sort Rows. In the Sort form, enter your sort criteria and click OK.
Try this:
SELECT * FROM stores ORDER BY country = "us" DESC, storeId
To get the searched-for country first, and the remainder alphabetically:
SELECT *
FROM stores
ORDER BY country = 'us' DESC, country ASC
You have to link each value of a country with a numeric, with a case :
select *
from stores
order by case when country = "us" then 1
else 0
end desc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With