Example table:
CREATE TABLE adj_list_model (
id INT NOT NULL AUTO INCREMENT,
parent_id INT,
my_string varchar(255),//some random information
PRIMARY KEY (id)
)
The tree I am creating will have multiple "root" users in the same table (when parent_id = NULL). These "root" users may at some point acquire a parent_id from some "leaf" user (user that has no one under them). The doubt I have is how to make sure that I don't create a "loop" similar to the following one:
Example Tree Design:
- a
- b
- c
- d
- e
- f
- g
if user "a" acquires user "g" as his Parent, then the loop created would be:
a -> c -> d -> f -> g -> a -> c... and so on forever
QUESTION: what's a good way to check if user "g" is under user "a" when user "a" wants go to under user "g" in the tree? (so that in those specific cases the action can be prevented)
Key points to consider: Having two trees merging into one would happen very often. If the number of levels in the tree where hypothetically 80, the amount of time it might take to do the checking to prevent loops might be considerable, which is why I am looking for an efficient method.
EDITED: The current options I have had (though I am skeptical) are:
Creating an extra column that shows the current "root" user for each user in the table. In those cases, every time a "root" user obtained a parent, everyone under him would have to be updated with the new "root" user, and what worries me is how much strain this might put on the server, especially if there are a lot of users and if there is a high frequency of "root" users obtaining a parent.
Checking a "root" users path before giving him a parent. If in the case above user "g" had his path checked by looping through each user above g 1 by 1 (seeing what their parent was, over and over until getting to the root), and found that the root was user "a", then yes, the action could be prevented, though I am not sure how straining this would be on the server. If anyone has an idea, let me know please!