Mysql-内部连接条件的索引

时间:2012-08-16 11:23:30

标签: mysql indexing inner-join

我有2张如下表

inv_ps
--------
inv_fkid  ps_fkid
1         2
1         4
1         5

other_table
----------
id   ps_fkid  amt  other_data
1     2       20   xxx
2     NULL    10   xxx
3     NULL    5    xxx 
4     5       6    xxx
5     4       7    xxxx

这是查询

SELECT inv_ps.ps_fkid, ot.amt FROM invoice_ps inv_ps INNER JOIN other_table ot ON ot.ps_fkid = inv_ps.ps_fkid WHERE inv_ps.inv_fkid=1 GROUP BY inv_ps.ps_fkid

这确实可行,但是当我查看EXPLAIN Sql

id  select_type       table     type        possible_keys       key        key_len      ref         rows        Extra
1   SIMPLE           inv_ps     ref         inv_fkid,ps_fkid    inv_fkid      4     const            1            Using where; Using temporary; Using filesort
1   SIMPLE            ot        ref         ps_fkid             ps_fkid       5     inv_ps.ps_fkid  3227       Using where

这应该只扫描3行,但为什么它在3227行中搜索,即使我在两个连接列上都添加了索引?是因为列 ot.ps_fkid 设置为 NULL

请解释

1 个答案:

答案 0 :(得分:1)

根据我的知识,只有在covering index

的情况下才会在GROUP BY子句中使用索引

尝试使用表格中的covering indexs进行解释:

ALTER TABLE other_table ADD INDEX ix1 (ps_fkid, amt);
ALTER TABLE invoice_ps ADD INDEX ix1 (inv_fkid, ps_fkid);

SELECT a.ps_fkid, b.amt
FROM  (SELECT ps_fkid
       FROM invoice_ps
       WHERE inv_fkid = 1
       GROUP BY ps_fkid
      )a
      INNER JOIN other_table b
         ON a.ps_fkid = b.ps_fkid;