是否可以对mysql中的特定单元格值进行排序?

jexiocij  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(287)

我需要使用mysql对下面的单元格值进行排序

例子:
细胞含有红,蓝,绿
但我要按字母顺序排列。

yeotifhr

yeotifhr1#

操作步骤,
1.首先,您需要调用一个过程来对值进行排序
2.那就叫你的程序
下面是创建mysql过程的代码

-- sort comma separated substrings with unoptimized bubble sort
DROP FUNCTION IF EXISTS sortString;
DELIMITER |
CREATE FUNCTION sortString(inString TEXT) RETURNS TEXT
BEGIN
  DECLARE delim CHAR(1) DEFAULT ','; -- delimiter 
  DECLARE strings INT DEFAULT 0;     -- number of substrings
  DECLARE forward INT DEFAULT 1;     -- index for traverse forward thru substrings
  DECLARE backward INT;   -- index for traverse backward thru substrings, position in calc. substrings
  DECLARE remain TEXT;               -- work area for calc. no of substrings
-- swap areas TEXT for string compare, INT for numeric compare
  DECLARE swap1 TEXT;                 -- left substring to swap
  DECLARE swap2 TEXT;                 -- right substring to swap
  SET remain = inString;
  SET backward = LOCATE(delim, remain);
  WHILE backward != 0 DO
    SET strings = strings + 1;
    SET backward = LOCATE(delim, remain);
    SET remain = SUBSTRING(remain, backward+1);
  END WHILE;
  IF strings < 2 THEN RETURN inString; END IF;
  REPEAT
    SET backward = strings;
    REPEAT
      SET swap1 = SUBSTRING_INDEX(SUBSTRING_INDEX(inString,delim,backward-1),delim,-1);
      SET swap2 = SUBSTRING_INDEX(SUBSTRING_INDEX(inString,delim,backward),delim,-1);
      IF  swap1 > swap2 THEN
        SET inString = TRIM(BOTH delim FROM CONCAT_WS(delim
        ,SUBSTRING_INDEX(inString,delim,backward-2)
        ,swap2,swap1
        ,SUBSTRING_INDEX(inString,delim,(backward-strings))));
      END IF;
      SET backward = backward - 1;
    UNTIL backward < 2 END REPEAT;
    SET forward = forward +1;
  UNTIL forward + 1 > strings
  END REPEAT;
RETURN inString;
END |
DELIMITER ;

要进行程序调用,必须使用,

-- example call:
SET @Xstr  = "red,blue,green"; // for query purpose only you need to write within (SQL Query here for that row)

SELECT sortString(@Xstr) AS s1

请参阅文档指南Map单击此处阅读
另外,如果你有兴趣学习的话,还有另外一种方法,那就是在\集中查找\请你从stackoverflow的一个问题中找到一些想法。单击此处阅读

fzwojiic

fzwojiic2#

您可以创建一个函数,对列中的项进行排序:

create function f_comma_list_order ( t text )
returns text
begin

declare v_c int;

drop temporary table if exists tmp;
create temporary table tmp ( v text );

set v_c = 1;

while( v_c > 0 ) do
  select locate(',', t) into v_c;

  if (v_c>0) then
    insert into tmp select substr(t, 1, v_c-1);
    set t = substr(t, v_c+1);
  else 
    insert into tmp values (t);
  end if;
end while;

select group_concat(v order by v) into t
from tmp;

return t;

end

然后调用函数:

select f_comma_list_order('red,green,blue')

相关问题