2012-08-16 49 views
1

我有2個表像下面在內Mysql-索引連接條件

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 

這確實工作得很好,但是當我查看解釋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

按我的知識索引用於在GROUP BY條款,只有當它是一個covering index

嘗試與表以下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; 
+0

剛剛添加的指標,但行數仍然相同 – jane 2012-08-16 11:40:54

+0

保持索引原樣並嘗試新更新的查詢。它應該給你更好的永久性。 – Omesh 2012-08-16 12:30:11