2016-03-04 66 views
1

例子:是否可以在MySQL中進行值排序?

如果我有一個數據庫表名爲productsproduct_title

zyx 
cba 
defabc 

我需要什麼樣的下名爲product_title

內容中的列?

`zyx` should be changed `xyz` 
`cba` should be changed `abc` 
`defabc` should be changed `abcdef` 

所有的值按字母順序排列。

我試過了嗎?

我試圖尋找要求,但我找不到任何解決方案。我只想知道「這是可能的」

如果這是不可能的,我如何排序我的記錄與最匹配的子字符串?

+0

不知道我是否理解。你想'更新'數據 - 'update table set field ='xyz'where field ='zyx''? – sgeddes

+0

試試這個功能 - Reverse() http://dev.mysql.com/doc/refman/5.7/en/string-functions.html – xardael

+0

不完全是@sgeddes,我們不能暫時將字段按字母排序訂購? – ameenulla0007

回答

1

沒有內置函數來對mysql中字符串中的符號進行排序。

反正你可以創建自己的存儲過程:

CREATE FUNCTION sv(
    x VARCHAR(255) 
) 
RETURNS VARCHAR(255) 
DETERMINISTIC 
BEGIN 
    declare r varchar(255); 
    declare maxlen int; 
    declare pos int; 
    declare sym char(1); 
    declare npos int; 

    set r = ""; 

    set maxlen = length(x); 
    set pos = 1; 
    while (pos <= maxlen) do 
     set sym = substr(x, pos, 1); 

     set npos = 1; 
     while ((npos <= length(r)) and (substr(r, npos, 1) < sym)) do 
      set npos = npos + 1; 
     end while; 
     set r = concat(substr(r, 1, npos-1), sym, substr(r, npos)); 

     set pos = pos + 1; 
    END while; 

    return r; 
END 

fiddle

它的工作原理很慢,要加快進程,我建議你創建新列product_title_sorted,運行update products set product_title_sorted=sv(product_title) where product_title_sorted is null

和然後在您的查詢中使用product_title_sorted

+0

這很好,但我想知道,這是否是以性能爲導向的? – ameenulla0007

+0

不,這是緩慢的做法 –

+0

哦!但感謝回覆和幫助@lashane。謝謝.. :) – ameenulla0007

相關問題