2015-12-19 28 views
4

例子:如何通过MySQL中的各种值进行排序?

---------------------------------------------- 
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 
---------------------------------------------- 

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

+0

其实P.No订单是好的。但我需要优先考虑第二顺序。 –

回答

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 
+0

非常感谢@RamRaider –

+0

欢迎 - 感谢@Nikos M添加更多细节 – RamRaider

5

你想翻译的三重(Self, Husband, Son)到的东西,那就是compareable。有几个方法可以做到这一点:

用简单的方式:

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

或者时髦的方式:

ORDER BY (Relation="Self")+2*(Relation="Husband")+3*(Relation="Son") 
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 
0

只是列出它们按优先顺序排列。

ORDER BY P.No,Name,Relation ASC 
相关问题