2016-11-20 49 views
1

我有哪裏一些值插入像這樣的舊數據庫:MySQL的ORDER BY刪除非數字字符

blablabla2008 
blablabla2010 
blablabla2011 

...的一些其他的(新)值插入爲數字:

2013 
2014 

有沒有辦法在sql查詢中對此進行排序?

回答

2

如果你關心的數字是最後四個字符(如你的例子),那麼這很簡單:

order by right(col, 4) 

否則,問題是更難,因爲MySQL不提供一種方法,查找或使用角色類。一種方法是這樣的:

order by (case when substring(col, -2, 1) not between '0' and '9' 
       then right(col, 1) + 0 
       when substring(col, -3, 1) not between '0' and '9' 
       then right(col, 2) + 0 
       when substring(col, -4, 1) not between '0' and '9' 
       then right(col, 3) + 0 
       when substring(col, -5, 1) not between '0' and '9' 
       then right(col, 4) + 0 
       . . . 
      end) 

也就是說,檢查每個位置的非數字字符。