如何在MySQL中按各种值排序?

时间:2015-12-19 10:12:00

标签: mysql sorting

示例:

----------------------------------------------
P.No     |     Relation   |  Name 
----------------------------------------------
2        |     Self       | Kumar
----------------------------------------------
1        |     Husband    | Selvam
----------------------------------------------
2        |     Son        |  Manoj
----------------------------------------------
1        |    Self        |   Gandhi
----------------------------------------------

如何基于列值首选项的行?

我想要这样的事情:

Order By P.No & 
 ( Self 1 st preference ,  
   Husband 2nd preference,
   son 3rd Preference ) 

我期待这个输出:

----------------------------------------------
P.No     |     Relation   |  Name 
----------------------------------------------
1        |      Self       |   Gandhi
----------------------------------------------
1        |     Husband    | Selvam
----------------------------------------------
2        |     Self       | Kumar
----------------------------------------------
2        |     Son        |  Manoj
----------------------------------------------

请帮我解决我的问题。谢谢。

4 个答案:

答案 0 :(得分:5)

您希望将三元组(Self, Husband, Son)翻译成可比较的内容。有几种方法可以做到这一点:

天真的方式:

ORDER BY IF(Relation="Self",0,IF(Relation="Husband",1,2))

或者时髦的方式:

ORDER BY (Relation="Self")+2*(Relation="Husband")+3*(Relation="Son")

答案 1 :(得分:4)

我认为你可能会做类似的事情:

order by p.`No`, `Relation`='Self', `Relation`='Husband', `Relation`='Son'

表达式Relation='Self'Relation='Husband'Relation='Son'返回01(按添加顺序),具体取决于是否满意。因此可以生成所需的排序

您还可以将FIELD function of MySQL用作:

order by p.`No` ASC, FIELD(`Relation`,'Self,Husband,Son') ASC

答案 2 :(得分:2)

请尝试以下查询

select *,if(Relation = 'Self',1,if(Relation = 'Husband',2,if(Relation = 'Son',3,4))) as rel_ord from table order by p.No asc ,rel_ord asc

答案 3 :(得分:0)

按优先顺序列出它们。

ORDER BY P.No,Name,Relation ASC