I have a big table on mysql (innodb) which contains products assets (13 millions of rows). Here a little schema of my database :
product <-many2one-- file_item --one2many--> family --many2one--> download_type
The *file_item* table is the big table with millions of rows. I try to count products by download types with the following sql query :
select t.name as type,
count(p.product_id) as n
from file_item p
inner join family f on f.id = p.family_id
inner join type t on f.id_type = t.id
group by t.id order by t.name;
There are 3 indexes on *file_item* table:
- product_family_idx (product_id, family_id)
- family_idx (family_id)
- product_idx (product_id) Explain output :
+----+-------------+-------+--------+-----------------------------------+---------+---------+-------------------+----------+---------------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------+--------+-----------------------------------+---------+---------+-------------------+----------+---------------------------------+ | 1 | SIMPLE | p | ALL | FAMILY_IDX,PRODUCT_FAMILY_IDX | NULL | NULL | NULL | 13862870 | Using temporary; Using filesort | | 1 | SIMPLE | f | eq_ref | PRIMARY,TYPE_ID | PRIMARY | 4 | MEDIA.p.FAMILY_IDX| 1 | | | 1 | SIMPLE | t | eq_ref | PRIMARY | PRIMARY | 4 | MEDIA.f.TYPE_ID | 1 | | +----+-------------+-------+--------+-----------------------------------+---------+---------+-------------------+----------+---------------------------------+
The query takes more than 1 hour to return the results. Please how I can optimize the query ?!