2012-04-21 50 views
0

排序VARCHAR字段試圖排序如下TEAM_TOTAL列說明對於MySQL數據庫

MATCHID  TEAM_TOTAL   
---------- ----------------- 
573   Total 112  
573   Total 2 for 115 
574   Total 9 for 97 
574   Total 2 for 100 
575   Total 9 for 129 
575   Total 9 for 101 
576   Total 4 for 191 
576   Total 9 for 160 
577   Total 8 for 157 
577   Total 7 for 137 
578   Total 6 for 193 
578   Total 119 

但問題是TEAM_TOTAL爲varchar,有沒有與查詢的方式獨自我可以在排序倒序結果。 那邊還有一段文字。我跑出去的想法,讓這件事

結果應該beeen像下面的結果集

MATCHID  TEAM_TOTAL   
    ---------- ----------------- 
    578   Total 6 for 193 
    576   Total 4 for 191 
    576   Total 9 for 160 
    577   Total 8 for 157 
    577   Total 7 for 137 
    575   Total 9 for 129 
    578   Total 119 
    573   Total 2 for 115 
    573   Total 112 
    575   Total 9 for 101 
    574   Total 2 for 100 
    574   Total 9 for 97 
+0

嘗試'SELECT * FROM表名ORDER BY TEAM_TOTAL' – 2012-04-21 08:11:02

+0

如何此列'Team_TOTAL'從您的查詢填充,您可以發佈它。 – 2012-04-21 08:11:03

+0

@FahimParkar,'Team_TOTAL'是'varchar'列,即會被alphapitacally排序,但OP希望它通過在數字後的對keywoard進行排序。 – 2012-04-21 08:12:18

回答

2

試試這個:

select * from t 
order by substring(
    team_total, locate('for', team_total) + 
     if(locate('for', team_total) > 0, 4, 7))+0 desc 

小提琴here

+1

非常感謝你這真的很棒,你是SQL GURU – gmhk 2012-04-21 08:52:56

0

嘗試提取(最後一個空格之後的字符串)的整數

-- 'Total 112' - extracts 112 
SELECT SUBSTRING('Total 112', LENGTH('Total 112') - LOCATE(' ', REVERSE('Total 112'))); 

-- 'Total 6 for 193' - extracts 193 
SELECT SUBSTRING('Total 6 for 193', LENGTH('Total 6 for 193') - LOCATE(' ', REVERSE('Total 6 for 193'))); 

現在,您可以將該字符串轉換爲數字,然後按順序排序。

SELECT * FROM teams 
ORDER BY 
CAST(SUBSTRING(TEAM_TOTAL, LENGTH(TEAM_TOTAL) - LOCATE(' ', REVERSE(TEAM_TOTAL))) AS INT) DESC