我正在尝试查询以按定义的类型,性别和名称排序的学生班级列表。

我有下一个查询:

SELECT * FROM STUDENTS
  ORDER BY FIELD(type, 'b', 'p', 'j', 'i', 'a', 'c', 'v'), FIELD(sex, 'M', 'F'), `name` ASC


我先得到那个顺序,首先是类型,然后是该类型和名称的性别,但是我需要一起定义一些类型和性别,如下所示:

type = 'b', sex = 'M', name
type = 'b', sex = 'F', name
type = 'p', sex = 'M', name
type = 'p', sex = 'F', name
type = 'i', sex = 'M', name
type = 'a', sex = 'M', name
type = 'c', sex = 'M', name
type = 'v', sex = 'M', name
type = 'j', sex = 'M', name
type = 'i', sex = 'F', name
type = 'a', sex = 'F', name
type = 'c', sex = 'F', name
type = 'v', sex = 'F', name
type = 'j', sex = 'F', name

最佳答案

您始终可以使用CASE语句创建所需的表达式

SQL DEMO

SELECT *
FROM Table1
ORDER BY CASE WHEN type = 'b' and sex = 'M' THEN 1
              WHEN type = 'b' and sex = 'F' THEN 2
              WHEN type = 'p' and sex = 'M' THEN 3
              WHEN type = 'p' and sex = 'F' THEN 4
              ....
              ELSE 9999
          END,
          name

关于mysql - SQL ORDER BY多个具有子顺序的字段,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47553538/

10-12 15:00