工做中,mysql字符串排序如何作?

1.問題由來

以下圖所示: 咱們的需求是根據 後綴的數字排序,由於不是純數字因此經常使用的解決方案例如,order by filed +1 ,或者是 order by CAST(server_id as SIGNED) desc 這種方案都是不可取的。
mysql


2.解題思路

   表結構: 
sql


默認數據:bash


   2.1定義規範

    和客戶(劃重點溝通很重要)探討以後,客戶說後面的數字 最可能是三個,最少2個。函數

    也是就 數據只會出現有 
ui

     例1:  興城10-1                   V
     例2:  興城10-101-123        V
spa

     反例1:興城10                      X
     反例2:新城10-1-123-13      X

   2.2利用mysql 字符串拆分機制

   示例數據:興城10-101-123code

   1.獲取第一個數字的位置 拆分紅  興城  和  10-101-123cdn

   利用 find_first_int(自定義的尋找第一個數字位置函數), 和 字符串截取server

CREATE DEFINER = 'root'@'localhost' FUNCTION `find_first_int`(
        pData CHAR(60)
    )
    RETURNS int(11)
    NOT DETERMINISTIC
    CONTAINS SQL
    SQL SECURITY DEFINER
    COMMENT ''
BEGIN
  DECLARE vPos INT DEFAULT 1;
  DECLARE vRes INT DEFAULT 0;
  DECLARE vChar INT;
  WHILE vPos <= LENGTH(pData) DO
    SET vChar = ASCII(SUBSTR(pData,vPos,1));
    IF vChar BETWEEN 48 AND 57 THEN
      RETURN vPos;
    END IF;
    SET vPos = vPos + 1;
  END WHILE;
  RETURN NULL;
END;複製代碼
select test,substring(test,find_first_int(test)) 截取後的 from `testtable`;
複製代碼

    

  2.把截取後的 分爲 one ,tow ,three 三個字段,興城10-101-123 對應的 onw = 10,two = 101,three = 123blog

select test,
LEFT(substring(test,Locate('1',test)  ),(LOCATE('-',substring(test,find_first_int(test)))-1)) one,

if(length(test)-length(replace(test,'-','')) = 1,
substring(substring(test,find_first_int(test)  ),(LOCATE('-',substring(test,find_first_int(test)))+1)) 
,
left(substring(substring(test,find_first_int(test)  ),(LOCATE('-',substring(test,find_first_int(test)))+1)),LOCATE( '-',substring(substring(test,find_first_int(test)  ),(LOCATE('-',substring(test,find_first_int(test)))+1)))-1 )
)two,

right(substring(substring(test,find_first_int(test)  ),(LOCATE('-',substring(test,find_first_int(test)))+1)),LOCATE( '-',substring(substring(test,find_first_int(test)  ),(LOCATE('-',substring(test,find_first_int(test)))+1)))-1 ) three

from `testtable`;

複製代碼

3.最後 order by one,two,three 就能夠獲得想要的排序結果拉

select test
from `testtable`
order by 
LEFT(substring(test,find_first_int(test)  ),(LOCATE('-',substring(test,find_first_int(test)))-1)) *1,
if(length(test)-length(replace(test,'-','')) = 1,
substring(substring(test,find_first_int(test)  ),(LOCATE('-',substring(test,find_first_int(test)))+1))*1 
,
left(substring(substring(test,find_first_int(test)  ),(LOCATE('-',substring(test,find_first_int(test)))+1)),LOCATE( '-',substring(substring(test,find_first_int(test)  ),(LOCATE('-',substring(test,find_first_int(test)))+1)))-1 ))*1
,
right(substring(substring(test,find_first_int(test)  ),(LOCATE('-',substring(test,find_first_int(test)))+1)),LOCATE( '-',substring(substring(test,find_first_int(test)  ),(LOCATE('-',substring(test,find_first_int(test)))+1)))-1 )*1
 ;複製代碼

總結

工做中會遇到不少問題,溝通很重要,其次就是解題思路。

最後我準備發 獲取 one ,two ,thrre 的地方小小封裝一下,畢竟看上去有點  亂0 0,封裝成函數會好點。

相關文章
相關標籤/搜索