按特定订单使用特定行值订购记录

时间:2017-12-24 00:57:05

标签: mysql sql

  Name     | Faction     |   Score
----------------------------------------
  Alpha    | Viva        |   7000
  Beta     | Rico        |   8000
  Bravo    | Morgan      |   9000
  Active   | Rico        |   10000
  Delta    | Edison      |   11000
  Siphon   | Viva        |   12000
  Taximus  | More        |   13000
  Ariticus | Viva        |   14000
  Ariticus | Havoc       |   15000

在此表中,我尝试按特定Faction首先排序数据,然后继续Score DESC,如下所示 [所有这些都是type=all]

SELECT Name, Score FROM memebers WHERE type = all GROUP BY id ORDER BY Faction = 'Viva' DESC, Faction = 'Rico' DESC, Score DESC

我期望得到的是

  Name     | Faction     |   Score
----------------------------------------
  Ariticus | Viva        |   14000
  Siphon   | Viva        |   12000
  Alpha    | Viva        |   7000
  Active   | Rico        |   10000
  Beta     | Rico        |   8000
  Ariticus | Havoc       |   15000
  Taximus  | More        |   13000
  Bravo    | Morgan      |   9000

但我一直只按Score DESC订购它们。

2 个答案:

答案 0 :(得分:5)

使用case表达式。

ORDER BY case when Faction = 'Viva' then 1
              when Faction = 'Rico' then 2
         else 3 end,
Score DESC

答案 1 :(得分:1)

对于mysql,如果Faction值列表很小,您也可以尝试ORDER BY FIELD(),并且可以在下面给出的参数中提供:

SELECT Name, Score 
FROM memebers 
WHERE type = all 
GROUP BY id 
ORDER BY FIELD(Faction, 'Viva', 'Rico', 'Havoc', 'More','Morgan'), Score DESC;