ast3r3x
2008-03-08, 21:23
So I have a question about how to query a tree like structure using MySQL. I am trying to figure out how to find all the child nodes give a single node. The diagram below is a sample of how table is structured. The format is node# : parent#. I've been trying to figure out how to find all the children of 3.
http://codingalchemy.com/files/chart.png
I found something similar to what I want to do here (http://www.webinade.com/web-development/creating-recursive-sql-calls-for-tables-with-parent-child-relationships) but in MS SQL, I guess you can't have a table reference itself before it is created because…well it doesn't exist.
Does anyone have any ideas how you'd do this in MySQL without using a procedure?
If you'd like my test table to play around with…
CREATE TABLE category_hierarchy (
category INT,
parent_cat INT,
PRIMARY KEY(category, parent_cat)
);
INSERT INTO category_hierarchy VALUES (1, 0);
INSERT INTO category_hierarchy VALUES (2, 1);
INSERT INTO category_hierarchy VALUES (3, 1);
#INSERT INTO category_hierarchy VALUES (3, 10);
INSERT INTO category_hierarchy VALUES (4, 1);
INSERT INTO category_hierarchy VALUES (5, 3);
INSERT INTO category_hierarchy VALUES (5, 2);
INSERT INTO category_hierarchy VALUES (6, 3);
INSERT INTO category_hierarchy VALUES (7, 2);
INSERT INTO category_hierarchy VALUES (8, 2);
INSERT INTO category_hierarchy VALUES (9, 6);
INSERT INTO category_hierarchy VALUES (10, 6);
http://codingalchemy.com/files/chart.png
I found something similar to what I want to do here (http://www.webinade.com/web-development/creating-recursive-sql-calls-for-tables-with-parent-child-relationships) but in MS SQL, I guess you can't have a table reference itself before it is created because…well it doesn't exist.
Does anyone have any ideas how you'd do this in MySQL without using a procedure?
If you'd like my test table to play around with…
CREATE TABLE category_hierarchy (
category INT,
parent_cat INT,
PRIMARY KEY(category, parent_cat)
);
INSERT INTO category_hierarchy VALUES (1, 0);
INSERT INTO category_hierarchy VALUES (2, 1);
INSERT INTO category_hierarchy VALUES (3, 1);
#INSERT INTO category_hierarchy VALUES (3, 10);
INSERT INTO category_hierarchy VALUES (4, 1);
INSERT INTO category_hierarchy VALUES (5, 3);
INSERT INTO category_hierarchy VALUES (5, 2);
INSERT INTO category_hierarchy VALUES (6, 3);
INSERT INTO category_hierarchy VALUES (7, 2);
INSERT INTO category_hierarchy VALUES (8, 2);
INSERT INTO category_hierarchy VALUES (9, 6);
INSERT INTO category_hierarchy VALUES (10, 6);