2
我有一些麻煩理解在嵌套集模型上使用哪些索引。查詢是:嵌套集指數和性能
SELECT `node`.`id`,(COUNT(parent.id) - 1) AS `depth`,`name` FROM `categories` AS `parent`
INNER JOIN `categories` AS `node` ON (`node`.`lft` BETWEEN parent.lft AND parent.rgt)
INNER JOIN `filebank_categories` ON (`node`.`id` = `filebank_categories`.`category_id` AND `filebank_categories`.`filebank_id` = 136)
INNER JOIN `categories_names` ON (`categories_names`.`category_id` = `node`.`id` AND `categories_names`.`language_id` = 1)
WHERE `node`.`system_id` = parent.system_id
GROUP BY node.id
ORDER BY `node`.`lft` ASC
該查詢在categories
需要用〜350ms的〜5000行。 EXPLAIN給出了這樣的:
1 SIMPLE filebank_categories ref fk_filebank_categories_categories1,filebank_id filebank_id 5 const 474 Using where; Using temporary; Using filesort 1 SIMPLE node eq_ref PRIMARY,lft,category,cat,lft,rgt,system,id,lft,system PRIMARY 4 filebank_categories.category_id 1 1 SIMPLE parent ref lft,category,system system 5 node.system_id 50 Using where 1 SIMPLE categories_names eq_ref PRIMARY,fk_categories_names_categories1 PRIMARY 8 node.id,const 1 Using where
表結構:
CREATE TABLE `categories` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`system_id` int(11) DEFAULT NULL,
`lft` int(11) DEFAULT NULL,
`rgt` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `lft,category` (`lft`,`id`),
KEY `cat,lft,rgt` (`id`,`lft`,`rgt`),
KEY `system` (`system_id`),
CONSTRAINT `categories_ibfk_1` FOREIGN KEY (`system_id`) REFERENCES `systems` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11519 DEFAULT CHARSET=utf8;
任何想法如何改進呢?它甚至有可能嗎?我在數據庫優化方面並不是很有經驗,因此我無法弄清楚在這裏使用哪些索引(以及爲什麼)。
感謝。
+1索引,舊密鑰'貓,LFT,rgt'( 'id','lft','rgt')無用於比較;此外,您可能希望停止在密鑰名稱中使用逗號 - 它使查閱計劃中可能的密鑰成爲一個有趣的練習。 – Unreason 2010-12-13 16:49:53
謝謝!這有助於查詢現在運行約100 ms。但是我仍然認爲「使用臨時文件;使用filesort」作爲「filebank_categories」,我認爲這是最慢的一切。 – 2010-12-14 12:16:16
filesort是好的(文件的名稱不太準確),使用臨時是由分組引起的 – ajreal 2010-12-14 16:13:31