开发者

MySQL: how to sort the words in a string using a stored function?

I need a MySQL stored function that sorts the words (separated by a space) in a string and return the sorted string.

For example : "The Quick Brown Fox" -> "Brown Fox Quick The"

In PHP this wo开发者_JS百科uld be an easy task, but in MySQL stored functions I can't use arrays, so I'm a bit stuck now. I could create a temp table, but this seems so overkill... (and slow).

Any idea's ?


Is this what you are looking for? http://psoug.org/snippet/mySQL-Sort-comma-separated-string_500.htm


Many thanks to Bob Vale !

I altered the function he suggested a little bit to specify a custom delimiter.

UPDATE:

This function is not perfect. It produces strangs results when the begin or end of the string is the same as the delimiter, and when there is more than 1 delimiter in a row in the string, so you'll have to make sure this is not the case in your strings.

CREATE FUNCTION `SPLIT_SORT`(inString TEXT, inSeparator TEXT)
 RETURNS text CHARSET utf8
BEGIN
  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(inSeparator, remain);
  WHILE backward != 0 DO
    SET strings = strings + 1;
    SET backward = LOCATE(inSeparator, 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,inSeparator,backward-1),inSeparator,-1);
      SET swap2 = SUBSTRING_INDEX(SUBSTRING_INDEX(inString,inSeparator,backward),inSeparator,-1);
      IF  swap1 > swap2 THEN
        SET inString = TRIM(BOTH inSeparator FROM CONCAT_WS(inSeparator
        ,SUBSTRING_INDEX(inString,inSeparator,backward-2)
        ,swap2,swap1
        ,SUBSTRING_INDEX(inString,inSeparator,(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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜