我有一個嵌套集模型分層數據(表:項目):MySQL的:優化找到嵌套集樹超級節點
我的表(項目):
id, lft, rgt
1, 1, 6
2, 2, 3
3, 4, 5
4, 7, 10
5, 8, 9
6, 11, 12
7, 13, 14
...
漂亮的印刷:
1
2
3
4
5
6
7
爲了找到節點3的最接近超級節點(知道它的價值LFT),我可以做
explain
SELECT projects.*
FROM projects
WHERE 4 BETWEEN projects.lft AND projects.rgt
這給了我一個到節點3的路徑中的項目列表。然後通過對結果進行分組和查找MAX(projects.lft),我得到最近的超級節點。但是,我似乎無法讓這個查詢運行得很快,它不會使用我定義的索引。 EXPLAIN說:
+----+-------------+----------+-------+----------------+----------+---------+------+------+--------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+----------+-------+----------------+----------+---------+------+------+--------------------------+
| 1 | SIMPLE | projects | index | lft,rgt,lftRgt | idLftRgt | 12 | NULL | 10 | Using where; Using index |
+----+-------------+----------+-------+----------------+----------+---------+------+------+--------------------------+
Mysql的瞭解什麼指標來使用,但仍必須通過所有10個行環(或在我的實際表100K)。
我怎樣才能讓MySql正確地優化這個查詢?我在下面包含一個測試腳本。
DROP TABLE IF EXISTS projects;
CREATE TABLE projects (
id INT NOT NULL ,
lft INT NOT NULL ,
rgt INT NOT NULL ,
PRIMARY KEY (id)
) ENGINE = MYISAM ;
ALTER TABLE projects ADD INDEX lft (lft);
ALTER TABLE projects ADD INDEX rgt (rgt);
ALTER TABLE projects ADD INDEX lftRgt (lft, rgt);
ALTER TABLE projects ADD INDEX idLftRgt (id, lft, rgt);
INSERT INTO projects (id,lft,rgt) VALUES (1,1,6);
INSERT INTO projects (id,lft,rgt) VALUES (2,2,3);
INSERT INTO projects (id,lft,rgt) VALUES (3,4,5);
INSERT INTO projects (id,lft,rgt) VALUES (4,7,10);
INSERT INTO projects (id,lft,rgt) VALUES (5,8,9);
INSERT INTO projects (id,lft,rgt) VALUES (6,11,12);
INSERT INTO projects (id,lft,rgt) VALUES (7,13,14);
INSERT INTO projects (id,lft,rgt) VALUES (8,15,16);
INSERT INTO projects (id,lft,rgt) VALUES (9,17,18);
INSERT INTO projects (id,lft,rgt) VALUES (10,19,20);
explain
SELECT projects.*
FROM projects
WHERE 4 BETWEEN projects.lft AND projects.rgt
你我的朋友,是個天才!你剛剛退休時保存了我們的數據庫服務器。你將進入學分表(yast.com),當我們做一個:) – Joernsn 2009-11-16 21:17:19
謝謝:)不要忘了添加一個鏈接到我的博客(http://explainextended.com):) – Quassnoi 2009-11-16 21:23:48