How to define a custom ORDER BY in MySQL query

时间:2016-03-02 11:01:08

标签: mysql

I need output in following order(firstly, group by last 3 letters and then arrange in order based on the first 3 digits)

ColumnA

001_eng
004_eng
002_chn
003_usa

But order by ColumnA gives me

ColumnA

001_eng
002_chn
003_usa
004_eng

This is just sample data. I have hundreds of entries in this format and the values keep changing everyday. So, specifying all the entries inside the field is not a feasible option. I'm not sure of how to use FIELD() in my case.

3 个答案:

答案 0 :(得分:1)

您可以使用FIELD:

select *
from tablename
order by
  FIELD(ColumnA, '001_eng', '004_eng', '002_chn', '003_usa')

(如果ColumnA不在列表中,请注意,字段函数将返回0并且行将放在顶部)

或者你可以使用CASE WHEN:

select *
from tablename
order by
  case
    when ColumnA='001_eng' then 1
    when ColumnA='004_eng' then 2
    when ColumnA='002_chn' then 3
    when ColumnA='003_usa' then 4
    else 5
  end

或者您可以使用指定顺序的其他语言表:

id | name    | sortorder
1  | 001_eng | 1
2  | 002_chn | 3
3  | 003_usa | 4
4  | 004_eng | 2

然后你可以使用连接

select t.*
from
  tablename t inner join languages l
  on t.lang_id = l.id
order by
  l.sortorder

(使用适当的索引,这将是具有最佳性能的更好解决方案)

答案 1 :(得分:0)

您可以使用substring()并通过

获取订单
SELECT * 
FROM table_name 
ORDER BY SUBSTRING(ColumnA, -7, 3);

答案 2 :(得分:0)

如果所有ColumnA值的格式都与示例数据类似,则可以使用SUBSTRING_INDEX

SELECT *
FROM mytable
ORDER BY FIELD(SUBSTRING_INDEX(ColumnA, '_', -1), 'eng', 'chn', 'usa'),
         SUBSTRING_INDEX(ColumnA, '_', 1)

Demo here