0

I have a bunch of a data in the following schema:

Id | category | remote_id
-------------------------

Where remote_id references another ID in the same table.

How can I query this so that for every record, I can find the distance to the root element thats defined as the row where the Id and remote_id are the same?

There is only one root in this data.

Can this be done purely through SQL without modifying this schema? Or is it necessary that I pull the data in memory into some server side application and model it like a conventional tree?

1 Answer 1

0

A procedure like this should work, though I haven't tested it:

CREATE PROCEDURE getDistanceToRoot
(
id INT
)
BEGIN
  DECLARE distance INT DEFAULT 0;
  DECLARE parentId INT DEFAULT NULL;
  SET parentId = (SELECT remoteid from table where id = id);
  WHILE (id != parentId) DO
    SET count = count + getDistanceToRoot(parentId);
    SET parentId = (SELECT remoteid from table where id = parentId);
 END WHILE;
  SELECT distance;
END;

It will also be slow. You could improve it's performance, once you tweak it to work (like I said I haven't tested it) by saving the distance for each id into a different table after getting it, as part of the procedure.

5
  • How can I view the result? What if i wanted to append the answer (distance to root) to a new column for each row? Right now I get an error here that says subquery returns more than 1 row. Oct 11, 2015 at 22:39
  • Also should mention the branching factor of the data is not fixed. Oct 11, 2015 at 22:53
  • This procedure definitely will not work. The idea would work, either as a procedure or function, but not as a hybrid. Oct 12, 2015 at 2:11
  • @GordonLinoff Why won't it work? Any suggestions on how to fix it? Oct 12, 2015 at 2:56
  • 1
    @AdamBronfin . . . Let's start with the observation that procedures do not return values. Oct 12, 2015 at 12:22

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.