本次的两个sql很简单,只是表的顺序不一样,一个是table2 left join table1,一个是table1 left join table2, 但是第一sql语句可以执行出来,第二个却不能执行出结果。
select * from table1 a left join table2 b on a.id = b.id where b.id is null;
select * from table2 a left join table1 b on a.id = b.id where b.id is null;
explain后发现sql2执行了全表查询,type 为all,possible_keys是null,表示未用到索引。
分析后发现原因是:
show full columns from table1;
table1使用的字符集是utf8_general_ci,table2使用的字符集是utf8mb4_general_ci。
修改字符集:
alter table table1 convert to character set utf8mb4 collate utf8mb4_general_ci
修改字符集后sql2 5ms就能查询出结果,sql1的速度也大大的加快了。
总结:
1. 字符集一定要一致。
2. 索引字段一定要非空。
3. 大表查询一定要有索引。