1

我有 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吗?

请解释

4

1 回答 1

1

根据我的知识,索引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;
于 2012-08-16T11:27:35.653 回答