这是非常简单的3张桌子。 我希望优化程序在contract.id上使用索引并拾取1行,并在拾取后加入其他表。 但是优化器不使用索引。为什么?
如何优化此查询以使用索引?
explain SELECT c.*, o.name FROM contract c
LEFT JOIN user u ON(c.user=u.id)
LEFT JOIN office o ON(u.office=o.id)
ORDER BY c.id LIMIT 0, 1
------------------ EXPLAIN结果-------------------
id select_type table partitions type possible_keys key key_len ref rows filtered Extra
1 SIMPLE c NULL ALL NULL NULL NULL NULL 12 100 Using temporary; Using filesort
1 SIMPLE u NULL ALL PRIMARY NULL NULL NULL 5 100 Using where; Using join buffer (Block Nested Loop)
1 SIMPLE o NULL eq_ref PRIMARY PRIMARY 4 u.office 1 100 NULL
------------------ MYSQL数据-------------------
CREATE TABLE `contract` (
`id` int(11) NOT NULL,
`user` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `contract` (`id`, `user`) VALUES
(1, 1),
(2, 3),
(3, 3),
(4, 2),
(5, 1),
(6, 3),
(7, 5),
(8, 3),
(9, 2),
(10, 1),
(11, 2),
(12, 3);
CREATE TABLE `office` (
`id` int(11) NOT NULL,
`name` varchar(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `office` (`id`, `name`) VALUES
(1, 'tokyo'),
(2, 'osaka'),
(3, 'kyoto'),
(4, 'fukushima'),
(5, 'hiroshima');
CREATE TABLE `user` (
`id` int(11) NOT NULL,
`office` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `user` (`id`, `office`) VALUES
(1, 3),
(2, 2),
(3, 1),
(4, 4),
(5, 3);
ALTER TABLE `contract` ADD PRIMARY KEY (`id`) USING BTREE;
ALTER TABLE `office` ADD PRIMARY KEY (`id`) USING BTREE;
ALTER TABLE `user` ADD PRIMARY KEY (`id`) USING BTREE;
ALTER TABLE `contract` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
ALTER TABLE `office` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
ALTER TABLE `user` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;