您的位置:首頁技術文章
文章詳情頁

mysql根據某個字段已存在的值排序

瀏覽:99日期:2022-06-14 16:45:36

問題描述

因為之前數據庫結構沒設計好,導致現在數據很混亂。1.就比如下面那個 values 字段,想讓他里面從小到大的排序。比如第一個變成 ['133','136','257']我知道php能做,但是我現在想研究一下mysql相關的函數,請問是否有支持的。。

因為我之前做 批量更新的時候,就發現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應該沒什么辦法,寫個腳本處理下吧。

相關文章:
国产综合久久一区二区三区