'Question Versions using CTE RECURSION MYSQL

Problem: An application for testing programmers contains an initial question version and newer question versions, represented by the following schema:

CREATE TABLE questions ( 
    id INTEGER NOT NULL PRIMARY KEY, 
    name VARCHAR(50) NOT NULL, 
    childId INTEGER, 
    FOREIGN KEY (childId) REFERENCES questions (id) 
); 

INSERT INTO questions (id, name, childId) 
VALUES 
(3, 'SQL select v3', NULL), 
(2, 'C# tuples', NULL), 
(1, 'SQL select v2', 3), 
(0, 'SQL select', 1);

The latest question version has childId set to NULL, other question versions will have childId set to the next version. Each question version can be a child of only one other question version.

Finish the findLatestVersion stored procedure so that it returns the latest question version.

Example case:

CALL findLatestVersion(0);
-- Expected output (in any order): 
-- 3

I need help to write the code



Solution 1:[1]

CREATE PROCEDURE findLatestVersion (IN question_id INT)
WITH RECURSIVE
cte AS (
    SELECT id, childId, 1 level
    FROM questions 
    WHERE id = question_id 
    UNION ALL
    SELECT questions.id, questions.childId, cte.level + 1
    FROM cte
    JOIN questions ON cte.childId = questions.id
)
SELECT cte.id
FROM cte
ORDER BY level DESC LIMIT 1;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1