Mysql两表关联不使用索引的问题

2020-11-05 15:23发布

问题:

两张表test_a,test_b结构和索引信息如下,通过主键inner join关联时,外表为什么不走索引呢?

create table test_a (
  id int,
  birthday date not null,
  comment varchar (50) not null,
  primary key test_a_pk (id),
  index test_a_index (birthday) 
) engine = innodb default charset = utf8;

create table test_b (
  id int,
  salary double not null,
  struct varchar (50) not null,
  primary key test_b_pk (id),
  index test_b_index (salary) 
) engine = innodb default charset = utf8;

mysql> show index from test_a\G
*************************** 1. row ***************************
        Table: test_a
   Non_unique: 0
     Key_name: PRIMARY
 Seq_in_index: 1
  Column_name: id
    Collation: A
  Cardinality: 5375084
     Sub_part: NULL
       Packed: NULL
         Null: 
   Index_type: BTREE
      Comment: 
Index_comment: 
*************************** 2. row ***************************
        Table: test_a
   Non_unique: 1
     Key_name: test_a_index
 Seq_in_index: 1
  Column_name: birthday
    Collation: A
  Cardinality: 2728
     Sub_part: NULL
       Packed: NULL
         Null: 
   Index_type: BTREE
      Comment: 
Index_comment: 
2 rows in set (0.00 sec)

mysql> show index from test_b\G
*************************** 1. row ***************************
        Table: test_b
   Non_unique: 0
     Key_name: PRIMARY
 Seq_in_index: 1
  Column_name: id
    Collation: A
  Cardinality: 5291561
     Sub_part: NULL
       Packed: NULL
         Null: 
   Index_type: BTREE
      Comment: 
Index_comment: 
*************************** 2. row ***************************
        Table: test_b
   Non_unique: 1
     Key_name: test_b_index
 Seq_in_index: 1
  Column_name: salary
    Collation: A
  Cardinality: 943640
     Sub_part: NULL
       Packed: NULL
         Null: 
   Index_type: BTREE
      Comment: 
Index_comment: 
2 rows in set (0.00 sec)

回答1:

“EQ_REF”就表示已经使用了主键索引了吧,建议做个实验,连接的另一个非主键id试试速度是否差不多。



回答2:

我用上面的sql语句创建的表,查询语句跟上面的也一样,但输出结果却相反,说明不是外表不用索引的问题,而是有一个表用了索引



回答3:

mysql不是有优化器么,有时候可能会分析到你这走索引还没有全表扫描效率高,就直接全表扫描了么