3

Is there a way to write recursive query in mysql. Equivalent of connect by (level or Prior) in oracle. I searched google as well as stackoverflow and there is no direct eqivalent. But is there any work around to get it.

I have a string, i have to iterate through individual characters in the string and print only the distinct characters of the string.

Input:

recursive

Output:

recusiv
3
  • Even if no straight answers, a little help or any direction to reach this is much appreciated. Commented Aug 29, 2013 at 7:44
  • Do you have a maximum possible string length? Commented Aug 29, 2013 at 7:56
  • No. String length is variable. But lets consider maximum length as 25. Commented Aug 29, 2013 at 9:08

1 Answer 1

4

I came up with this "simple" solution.

Functions used:

Live demo: http://www.sqlfiddle.com/#!2/d41d8/19186

SELECT
  GROUP_CONCAT( chars.c SEPARATOR '') AS allchars
FROM (

  SELECT DISTINCT 
    SUBSTRING( str.str, pos.pos, 1 ) AS c

  FROM 

  ( SELECT x1.x + x2.x*10 AS pos
    FROM
    ( SELECT 0 AS x UNION ALL
      SELECT 1 UNION ALL
      SELECT 2 UNION ALL
      SELECT 3 UNION ALL
      SELECT 4 UNION ALL
      SELECT 5 UNION ALL
      SELECT 6 UNION ALL
      SELECT 7 UNION ALL
      SELECT 8 UNION ALL
      SELECT 9
    ) AS x1
    INNER JOIN
    ( SELECT 0 AS x UNION ALL
      SELECT 1 UNION ALL
      SELECT 2 UNION ALL
      SELECT 3 UNION ALL
      SELECT 4 UNION ALL
      SELECT 5 UNION ALL
      SELECT 6 UNION ALL
      SELECT 7 UNION ALL
      SELECT 8 UNION ALL
      SELECT 9
    ) AS x2
  ) AS pos

  INNER JOIN

  ( SELECT 'recursive' AS str UNION ALL
    SELECT 'XYZ'
  ) AS str

) AS chars
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you. I get the picture now. Its very helpful.
@ToolmakerSteve: This disgusting query generates numbers 00..99 which are used as the character positions of the input strings (recursive and XYZ). SELECT DISTINCT SUBSTRING makes a table of one string's character which table is re-joined to a string by the outer GROUP_CONCAT. Seriously, it doesn't seem to be a good idea to do it in MySQL, unless they have some new functions since.
lol - ok I was curious. No new functions available that help this, agreed this is absurd task for sql. I have a one-off situation where I wanted to find out what characters are currently used in a name field - see if "bad" data was there. Decided to write the php test script, rather than debug an obscure mysql query.
@ToolmakerSteve: You did the right thing! :) Maybe regular expressions could be used to find values with "strange" values: dev.mysql.com/doc/refman/8.0/en/regexp.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.