Is there a way to join few results sets in to a one result set? I have a table with recursive relation.
eg. User table has a column with boss with the relation to the same
User table
When you pass the user id to the stored procedure it will find the relevant boss for that user and then again using boss as the user id finds his boss and again his boss and so on till it reaches the top so I can get all user ids of the bosses. now what I need is a way to union these results to a single table
So I will get the user list as a table. Example:
If I call:
the result should be like
This returns all the bosses above him.
Regards
Chathura Bamunusinghe.
eg. User table has a column with boss with the relation to the same
User table
Code:
+-------+---------------+-------+ | id | name | boss | +-------+---------------+-------+ | 1 | User 1 | NULL | | 2 | User 2 | 1 | | 3 | User 3 | 2 | | 4 | User 4 | 3 | | 5 | User 5 | 4 | | 6 | User 6 | 5 | | 7 | User 7 | 6 | | 8 | User 8 | 7 | | 9 | User 9 | 8 | +-------+---------------+-------+
Code:
DELIMITER // DROP PROCEDURE IF EXISTS getUserList// CREATE PROCEDURE getUserList(IN UserId int(32)) BEGIN DECLARE done INT DEFAULT 0; DECLARE intUser, intBoss INT; DECLARE cur_users CURSOR FOR SELECT `id`, `boss` FROM User WHERE `id` = UserId; DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; OPEN cur_users; REPEAT FETCH cur_users INTO intUser, intBoss; IF intBoss != NULL THEN SELECT intUser as `User`; CALL getUserList(intBoss); END IF; UNTIL done END REPEAT; CLOSE cur_users; END // DELIMITER ;
So I will get the user list as a table. Example:
If I call:
Code:
getUserList(5);
Code:
+-------+ | User| +-------+ | 1 | | 2 | | 3 | | 4 | | 5 | +-------+
Regards
Chathura Bamunusinghe.
Comment