mysql根據(jù)某個(gè)字段已存在的值排序
問題描述
因?yàn)橹皵?shù)據(jù)庫結(jié)構(gòu)沒設(shè)計(jì)好,導(dǎo)致現(xiàn)在數(shù)據(jù)很混亂。1.就比如下面那個(gè) values 字段,想讓他里面從小到大的排序。比如第一個(gè)變成 ['133','136','257']我知道php能做,但是我現(xiàn)在想研究一下mysql相關(guān)的函數(shù),請(qǐng)問是否有支持的。。
因?yàn)槲抑白?批量更新的時(shí)候,就發(fā)現(xiàn)mysql有這個(gè)辦法,感覺很強(qiáng)大
問題解答
回答1:寫個(gè)MySQL函數(shù),在里面拆字符串,排序。
例如可以這樣:
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);
(上面的函數(shù)假設(shè)了數(shù)字都是3位,不用直接用哦)
MySQL 5.7支持JSON了,把字段轉(zhuǎn)成JSON也許可以。
回答2:表設(shè)計(jì)的的時(shí)候就應(yīng)該保證這個(gè)值的原子性、這是設(shè)計(jì)上的失誤,mysql不會(huì)為這種失誤出解決方案吧
回答3:靠mysql應(yīng)該沒什么辦法,寫個(gè)腳本處理下吧。
相關(guān)文章:
1. css - 關(guān)于div自適應(yīng)問題,大家看圖吧,說不清2. python - django如何每次調(diào)用標(biāo)簽的時(shí)候都取隨機(jī)數(shù)據(jù)3. 關(guān)docker hub上有些鏡像的tag被標(biāo)記““This image has vulnerabilities””4. docker images顯示的鏡像過多,狗眼被亮瞎了,怎么辦?5. docker-machine添加一個(gè)已有的docker主機(jī)問題6. mysql - msyql 判斷字段不為空 簡(jiǎn)單方法7. html5 - vue 里的Elemen UI的時(shí)間怎么轉(zhuǎn)化為時(shí)間戳嗎8. angular.js使用$resource服務(wù)把數(shù)據(jù)存入mongodb的問題。9. javascript - Vue 自定義控件v-model雙向綁定10. linux - mysql源碼安裝遇到的問題
