performance - How to tune self-join table in mysql like this? -
i have table i'm trying select , date. query took 2 min run on 4 million records. i'm not sure how more can squeeze out of query.
select c.fk_id, c.from_date, c.fk_pb, min(o.from_date) to_date table_x c inner join table_x o on c.fk_id = o.fk_id , c.fk_pb = o.fk_pb o.from_date > c.from_date group c.fk_id, c.from_date, c.fk_pb
there indexes on from_date, fk_pb , fk_id already.
the schema this.
+-----------------------------+---------------+------+-----+---------+-------+ | field | type | null | key | default | | +-----------------------------+---------------+------+-----+---------+-------+ | fk_id | int(11) | yes | mul | null | | | fk_pb | int(11) | yes | mul | null | | | from_date | date | yes | mul | null | | | to_date | date | yes | | null | | +-----------------------------+---------------+------+-----+---------+-------+
i know should not use self-join @ in mysql, data comes , i'm trying find best way select , date out of table. if there's else make 1 faster that'd great.
thanks lot.
updated
+----+-------------+-------+------+----------------------------------------------------------------------+-------------------------+---------+----------------------------------------+---------+----------------------------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | | +----+-------------+-------+------+----------------------------------------------------------------------+-------------------------+---------+----------------------------------------+---------+----------------------------------------------+ | 1 | simple | c | | idx_fk_pb,idx_fk_id,idx_frm_date | null | null | null | 4527750 | using where; using temporary; using filesort | | 1 | simple | o | ref | idx_fk_pb,idx_fk_id,idx_frm_date | idx_fk_id | 5 | db.c.fk_id | 110 | using | +----+-------------+-------+------+----------------------------------------------------------------------+-------------------------+---------+----------------------------------------+---------+----------------------------------------------+
adding index relevant columns speeds up:
index(fk_id, fk_pb,from_date)
which performs better because:
- mysql can use index rows
c
, doesn't need go table (adding column not in index slow down again bit). - mysql pretty bad @ index merging, , chooses not use (luckily), , when it's suboptimal.
- well, index covering search (in case, join on = searching for) faster mysql electing 1 of indexes (the restrictive one,
show index tablename
can show cardinality) on separate columns use , having scan values in other columns.
Comments
Post a Comment