Sort certain values to the top

怎甘沉沦 提交于 2019-12-05 19:02:49

问题


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?


回答1:


Try this:

SELECT * FROM stores ORDER BY country = "us" DESC,  storeId



回答2:


To get the searched-for country first, and the remainder alphabetically:

SELECT * 
FROM   stores 
ORDER BY country = 'us' DESC, country ASC



回答3:


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



回答4:


Create a table of country codes and orders, join to it in your query, and then order by the country code's order.

So you would have a table that looks like

CountryOrder

Code  Ord
----  ---
us    1
jp    2
se    3

and then code that looks like:

SELECT s.*
FROM Stores s
INNER JOIN CountryOrder c
   ON c.Code = s.Country
ORDER BY c.Ord;



回答5:


How about using IF to assign the top value to US rows.

select if(country_cd='us,'aaaUS',country_cd) sort_country_cd, country_cd from stores Order by sort_country_cd

This will give you a pseudo column called sort_country_cd . Here you can map "US" to "aaaUS". JP can still be mapped to JP.

That puts US on the top of your sort list.



来源:https://stackoverflow.com/questions/1079068/sort-certain-values-to-the-top

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!