2013-07-01 71 views
2

我想在表中的行通過colomn 「值」,其中字段= 「訂單」 進行排序,通過的ObjectId分組行:MySQL的排序行的記錄組

Id | ObjectId | Field | Value 
------------------------------ 
1 | 1  | size | big 
2 | 1  | order | 2 //unsorted 
3 | 2  | size | small 
4 | 2  | order | 1 //unsorted 
5 | 3  | size | medium 
6 | 3  | order | 3 //unsorted 

預期結果:

Id | ObjectId | Field | Value 
------------------------------ 
3 | 2  | size | small 
4 | 2  | order | 1 //sorted 
1 | 1  | size | big 
2 | 1  | order | 2 //sorted 
5 | 3  | size | medium 
6 | 3  | order | 3 //sorted 

回答

0

您需要的字段值加入尺寸爲第一:

select t.* 
from t join 
    (select t.object_id, max(case when field = 'order' then value end) as ordering 
     from t 
     group by t.object_id 
    ) tsum 
    on t.object_id = tsum.object_id 
order by tsum.ordering, t.object_id, id; 

這就賦予相同的「排序」一切以相同object_id