创建表
其余俩张边在双表优化的案例说过,过去直接复制即可
CREATE TABLE IF NOT EXISTS `phone` ( `phoneid` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, `card` INT(10) UNSIGNED NOT NULL, PRIMARY KEY (phoneid) );
模拟数据
INSERT INTO phone(card) VALUES(FLOOR(1 + (RAND() * 20))); INSERT INTO phone(card) VALUES(FLOOR(1 + (RAND() * 20))); INSERT INTO phone(card) VALUES(FLOOR(1 + (RAND() * 20))); INSERT INTO phone(card) VALUES(FLOOR(1 + (RAND() * 20))); INSERT INTO phone(card) VALUES(FLOOR(1 + (RAND() * 20))); I INSERT INTO phone(card) VALUES(FLOOR(1 + (RAND() * 20)));
查询语句
select * from class left join book on class.card=book.card left join phone on book.card=phone.card
explain select * from class left join book on class.card=book.card left join phone on book.card=phone.card
# 创建索引 create index ind_card on book(card) create index ind_card on phone(card) # 查看索引 show index from book show index from phone
此次优化总结
- 在进行双表联查时我们使用了left join
- 第一次在左边的表加了索引
- 但是没有效果
- 这是由左连接的特性决定的,left join 是明确左边表的数据肯定都有,从右边表进行查询数据
- 所以右边是关键,我们一定要加上索引
- 那么三表查询也是同样的,反正记住一点,左连接加右表,右连接加到左表
- 小表驱动大表