tru*_*ppo 9 mysql sql-order-by
我有一个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');
Run Code Online (Sandbox Code Playgroud)
现在,我希望能够获得以客户所在国家/地区开头的分页商店列表.
例如,美国客户会看到以下列表:
Foo
Baz
Bar
Foo2
Baz2
Bar3
Run Code Online (Sandbox Code Playgroud)
我现在正在使用的天真解决方案(例如美国客户和页面大小3):
(SELECT * FROM stores WHERE country = "us") UNION (SELECT * FROM stores WHERE country != "us") LIMIT 0,3
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来做到这一点?可以ORDER BY使用,并告诉在顶部放有一定的价值?
Joa*_*uer 15
试试这个:
SELECT * FROM stores ORDER BY country = "us" DESC, storeId
Run Code Online (Sandbox Code Playgroud)
要首先获取搜索到的国家,然后按字母顺序获取其余的国家:
SELECT *
FROM stores
ORDER BY country = 'us' DESC, country ASC
Run Code Online (Sandbox Code Playgroud)