CREATE TABLE test1 (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(20) DEFAULT NULL,
code varchar(50) DEFAULT NULL,
PRIMARY KEY (id),
KEY idx_code (code),
KEY idx_name (name)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
CREATE TABLE test2 (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(20) DEFAULT NULL,
code varchar(50) DEFAULT NULL,
PRIMARY KEY (id),
KEY idx_code (code),
KEY idx_name (name)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4;
1.
explain select * from test1 join test2 on test1.code = test2.code where test1.name = 'xxx';
explain select * from test1 join test2 on test1.code = test2.code where test2.name = 'xxx';
为什么第一条语句,test1 可以用上索引,第二条语句 test1 用不上索引。
2.
explain select * from test2 join test1 on test1.code = test2.code where test1.name = 'xxx';
explain select * from test2 join test1 on test1.code = test2.code where test2.name = 'xxx';
为什么第一条语句,test1 可以用上索引,第二条语句 test1 用不上索引。
上面2种情况,test1 的 code 字段都用不上索引,什么时候test1 字段可以用上索引。