Question

I have one table with thousands of entries, many in a hierarchy form.

I am looking for a way to input the head level of several specific family trees into a query, search for all of their children, their children's children etc until no rows remain, and then insert each id into another table 12 times.

Numbered (AID, id1, 1) (AID , id1, 2)...(AID, id1, 11)(AID, id1, 12)

I have been trying to put together this query as a test to help find the required id's, with the end goal to be able to locate each descendant and insert each into another table x12 times. But with very little success. Any ideas?

....for the right syntax to use near ''parent_id' FROM test AS t JOIN acc2 as r on t.parent_id = r.id; ' at line 25

Is my current error message

(Absolute Amateur)

DROP PROCEDURE IF EXISTS find_descendants ()
DELIMITER GO
CREATE PROCEDURE find_descendants ()
BEGIN

DROP TABLE IF EXISTS acc;

CREATE TEMPORARY TABLE acc

SELECT id, parent_id, 0 as level
FROM test

WHERE id = 2;

ALTER TABLE acc ADD primary key (id,parent_id);

REPEAT

DROP TABLE IF EXISTS acc2;

CREATE temporary table acc2

SELECT * FROM acc;

INSERT INTO acc2

SELECT t.id, r.'parent_id'

FROM test AS t

JOIN acc2 AS r ON t.parent_id = r.id;

UNTIL Row_count () = 0 END REPEAT;

END;

go

DELIMITER;
CALL find_descendants ();

SELECT * FROM acc;

After this, I get the error #1137 "can't reopen table 'acc2'" which seems to invalidate the whole process !

Was it helpful?

Solution

You have syntax error in INSERT query

INSERT INTO acc2
SELECT t.id, r.'parent_id' /*--COMMENT : remove '' from 'parent_id' , it should be r.parent_id */
FROM test AS t
JOIN acc2 AS r ON t.parent_id = r.id;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top