将特定的值排在前面

9

我有一个MySQL表格,其中包含以下数据(简化):

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');

现在,我希望能够获取一个分页的商店列表,以客户所在国家为起点。
例如,美国客户将看到以下列表:
Foo
Baz
Bar
Foo2
Baz2
Bar3

我现在正在使用的天真解决方案(以一个美国客户和页面大小为3的例子):
(SELECT * FROM stores WHERE country = "us") UNION (SELECT * FROM stores WHERE country != "us") LIMIT 0,3

有没有更好的方法来做这件事?可以使用ORDER BY并告诉它将某个值放在顶部吗?

5个回答

16

试一下这个:

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

5

首先获取搜索到的国家,然后按字母顺序排序其余国家:

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

2

您需要将每个国家的值与数字进行关联,并使用case语句:

select *
from stores
order by case when country = "us" then 1
              else 0
         end desc

1
创建一个国家代码和订单的表格,在查询中加入它,然后按照国家代码的顺序排序。
因此,您将拥有一个类似于以下的表格:
CountryOrder

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

然后是类似这样的代码:

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

1

使用IF将顶部值分配给美国行,如何?

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

这将为您提供一个名为sort_country_cd的伪列。 在这里,您可以将“US”映射到“aaaUS”。 JP仍然可以映射到JP

这将把美国放在您的排序列表的顶部。


SELECT country_code, country_name FROM country ORDER BY IF (country_code IN ('CA', 'US'), 0,1), country_name按照IF(country_code IN ('CA', 'US'), 0,1)、country_name的顺序从country表中选择country_code和country_name。 - Shawn H

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接