可以在mySql中对特定的单元格值进行排序吗?

问题描述 投票:0回答:2

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

enter image description here

例:

  • 细胞含有红色,蓝色,绿色
  • 但我想按字母顺序排列。
mysql mysql-workbench
2个回答
1
投票

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

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')

3
投票

这样做的步骤,

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

请参阅文档指南地图Click here to read

还有另一种方法可以做,如果你有兴趣研究关于FIND_IN_SET,请你可以从stackoverflow的问题中找到一些想法。 Click here to read

© www.soinside.com 2019 - 2024. All rights reserved.