請幫我選索引表,以避免發生運行特定的查詢filesorting。優化索引來避免使用filesorting
所以,有兩個表demo_user
和demo_question
:
CREATE TABLE `demo_user` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50) NOT NULL,
`age` INT(11) NOT NULL,
PRIMARY KEY (`id`),
INDEX `age` (`age`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB;
CREATE TABLE `demo_question` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`userId` INT(11) NOT NULL,
`createdAt` DATETIME NOT NULL,
`question` VARCHAR(50) NOT NULL,
PRIMARY KEY (`id`),
INDEX `userId` (`userId`),
INDEX `createdAt` (`createdAt`),
CONSTRAINT `FK_demo_question_demo_user` FOREIGN KEY (`userId`) REFERENCES `demo_user` (`id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB;
一些樣本數據:
INSERT INTO `demo_user` VALUES ('u1', 20);
INSERT INTO `demo_user` VALUES ('u2', 25);
INSERT INTO `demo_user` VALUES ('u3', 27);
INSERT INTO `demo_user` VALUES ('u4', 33);
INSERT INTO `demo_user` VALUES ('u5', 19);
INSERT INTO `demo_question` VALUES (2, '2014-01-19 15:17:13', 'q1');
INSERT INTO `demo_question` VALUES (3, '2014-01-19 15:17:43', 'q2');
INSERT INTO `demo_question` VALUES (5, '2014-01-19 15:17:57', 'q3');
在這些表中,我試圖運行下面的查詢:
select *
from demo_question q
left join demo_user u on q.userId = u.id
where u.age >= 20 and u.age <= 30
order by q.createdAt desc
嘗試按0123排序結果時,此查詢的說明檢測到filesort列
+----+-------------+-------+------+---------------+------+---------+------+------+---------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+---------------+------+---------+------+------+---------------------------------+
| 1 | SIMPLE | q | ALL | userId | NULL | NULL | NULL | 3 | Using temporary; Using filesort |
| 1 | SIMPLE | u | ALL | PRIMARY,age | NULL | NULL | NULL | 5 | Using where; Using join buffer |
+----+-------------+-------+------+---------------+------+---------+------+------+---------------------------------+
所以我的問題:什麼可以做,以防止filesorting在運行這樣的查詢,因爲它會降低性能時,有兩個表格中較大的行數?
嘗試將其與內部聯接,而不是一個左連接,以防MySQL的是太愚蠢地看到,它這樣做,反正。 –
@Denis不幸的是內部聯接不會改變任何東西 – gatisl
嘗試把兩列到inndex,而不是2個指標上demo_question即INDEX'userId'('userId')成爲INDEX'userId'('userId','createdAt') –