2012-12-12 116 views
1

我有一個包含多個列的表,其中四個只是泛型整數值(num1,num2,num3,num4),數據源以隨機順序包含這些值。在PHP中,我將獲取該行,將四個整數分配給一個數組,對數組進行排序,並將排序的值分配回來並保存該行。我想用sql做到這一點。因此,與像Mysql - 用sql重新排列列值

id, num1, num2, num3, num4 
1 6  2 9  1 
2 12  3 8  4 

表...

我想結果是

id, num1, num2, num3, num4 
1  1  2  6  9 
2  3  4  8 12 

...

我用Google搜索一切我能想到的沖刷Mysql ref手冊,但似乎無法找到一種方法來做到這一點。任何想法,或者我應該只寫一個PHP腳本?

回答

0

嗯,這是一個UNPIVOT,排序和樞軸,但去年我在mysql中沒有聽到這樣 也許

Set @position = 0 
CREATE TEMPORARY TABLE OrderedUnpivot AS (
    Select Id,@position = @position + 1, @position % 4 as Position, Value From 
    (
    Select Id,Position,Value From 
    (
     select Id, 1 as Position, num1 as Value 
     Union 
     select Id, 2, num2 
     union 
     select Id, 3, num3 
     union 
     select Id, 4, num4 
    ) depivot 
    Order by Id, Value 
) 
Select ID,V1.Value as Num1, V2.Value as Num2, V3.Value as Num3, V4.Value as Num4 
From OrderedUnpivot v1 
Inner join OrderedUnpivot v2 ON v1.Id = v2.ID 
Inner join OrderedUnpivot v3 ON v1.Id = v3.ID 
Inner join OrderedUnpivot v4 ON v1.Id = v4.ID 

麻煩但回味無窮,哦,不測試,甚至語法檢查。