mysql根據某個字段已存在的值排序
問題描述
因為之前數據庫結構沒設計好,導致現在數據很混亂。1.就比如下面那個 values 字段,想讓他里面從小到大的排序。比如第一個變成 ['133','136','257']我知道php能做,但是我現在想研究一下mysql相關的函數,請問是否有支持的。。
因為我之前做 批量更新的時候,就發現mysql有這個辦法,感覺很強大

問題解答
回答1:寫個MySQL函數,在里面拆字符串,排序。
例如可以這樣:
CREATE FUNCTION `sort_col`(`input` VARCHAR(50)) RETURNS VARCHAR(50) LANGUAGE SQL NOT DETERMINISTIC NO SQL SQL SECURITY DEFINER COMMENT ’’BEGINdeclare a int;declare b int;declare c int;set a = cast(substr(input, 3, 3) as int);set b = cast(substr(input, 9, 3) as int);set c = cast(substr(input, 15, 3) as int);if (a <= b && b <= c) then return concat(’['’, a, ’','’, b , ’','’, c , ’']’);elseif (b <= a && a <= c) then return concat(’['’, b, ’','’, a , ’','’, c , ’']’);elseif (c <= a && a <= b) then return concat(’['’, c, ’','’, a , ’','’, b , ’']’);elseif (c <= b && b <= a) then return concat(’['’, c, ’','’, b , ’','’, a , ’']’);elseif (a <= c && c <= b) then return concat(’['’, a, ’','’, c , ’','’, b , ’']’);elseif(b <= c && c <= a) then return concat(’['’, b, ’','’, c , ’','’, a , ’']’);end if;END
然后就可以更新了:
update table_name set values = sort_col(values);
(上面的函數假設了數字都是3位,不用直接用哦)
MySQL 5.7支持JSON了,把字段轉成JSON也許可以。
回答2:表設計的的時候就應該保證這個值的原子性、這是設計上的失誤,mysql不會為這種失誤出解決方案吧
回答3:靠mysql應該沒什么辦法,寫個腳本處理下吧。
相關文章:
1. docker鏡像push報錯2. 關docker hub上有些鏡像的tag被標記““This image has vulnerabilities””3. html5 - datatables 加載不出來數據。4. Docker for Mac 創建的dnsmasq容器連不上/不工作的問題5. node.js - mongodb查找子對象的名稱為某個值的對象的方法6. docker 下面創建的IMAGE 他們的 ID 一樣?這個是怎么回事????7. 運行python程序時出現“應用程序發生異常”的內存錯誤?8. html5和Flash對抗是什么情況?9. 測試自動化html元素選擇器元素ID或DataAttribute [關閉]10. 前端 - @media query 使用出現的問題?

網公網安備