在MySQL中處理樹形數據通常使用兩種方法:鄰接表模型和閉包表模型。
示例:
CREATE TABLE tree (
id INT PRIMARY KEY,
parent_id INT,
name VARCHAR(50),
FOREIGN KEY (parent_id) REFERENCES tree(id)
);
-- 查詢節點及其所有子節點
SELECT t1.*, t2.*
FROM tree t1
LEFT JOIN tree t2 ON t1.id = t2.parent_id
WHERE t1.id = 1;
示例:
CREATE TABLE tree (
id INT PRIMARY KEY,
name VARCHAR(50)
);
CREATE TABLE tree_closure (
ancestor_id INT,
descendant_id INT,
PRIMARY KEY (ancestor_id, descendant_id),
FOREIGN KEY (ancestor_id) REFERENCES tree(id),
FOREIGN KEY (descendant_id) REFERENCES tree(id)
);
-- 查詢節點及其所有子節點
SELECT t1.*, t2.*
FROM tree t1
JOIN tree_closure tc ON t1.id = tc.ancestor_id
JOIN tree t2 ON tc.descendant_id = t2.id
WHERE t1.id = 1;
無論使用鄰接表模型還是閉包表模型,都需要額外的查詢和處理來處理樹形數據結構。根據實際需求和數據量的大小,選擇合適的方法來處理MySQL中的樹形數據。