问题描述
我在MySQL中有一个列表,该列表按字母顺序排序,如下所示.
I have a list in MySQL that is sorted in alphabetical order as follows.
- 阿根廷
- 巴西
- 中国
- 马耳他
- 美国
由于我的客户来自美国,所以我希望它首先显示在列表中,例如
Since the magority of my customers are from the USA, I want it to be displayed first in the list e.g.
- 美国
- 阿根廷
- 巴西
- 中国
- 马耳他
这是我的代码-
$sqlprimaryCategory = $dbh->prepare("SELECT * FROM $tableName GROUP BY primary_category ");
这是我尝试过但没有奏效的- $ sqlprimaryCategory = $ dbh-> prepare("SELECT * FROM $ tableName GROUP BY primary_category ORDER BY primary_category ='USA'ASC,primary_category ASC");
This is what I tried but did not work - $sqlprimaryCategory = $dbh->prepare("SELECT * FROM $tableName GROUP BY primary_category ORDER BY primary_category='USA' ASC, primary_category ASC");
推荐答案
只需使用诸如此类的case语句进行条件排序即可
just do a conditional order by with a case statement like so
SELECT *
FROM $tableName
GROUP BY primary_category
ORDER BY
CASE primary_category WHEN 'USA' THEN 1 ELSE 2 END ASC,
primary_category ASC
如果要先按多个字段排序,然后再按其余字段排序,则可以这样做.
if you want to order by multiple fields first and then the rest you can do it like this.
SELECT *
FROM $tableName
GROUP BY primary_category
ORDER BY
CASE primary_category
WHEN 'USA' THEN 1 --#-- 1 for usa
WHEN 'China' THEN 2 --#-- 2 for china
ELSE 3 END ASC, --#-- 3 for anything else
primary_category ASC
这篇关于MySQL显示结果按字母顺序排列,但在按字母顺序排列的列表之前显示特定项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!