sql - Can this MySQL join query be optimized? -
i have query takes 27 seconds execute:
select ocal_files.*, count(distinct ocal_favs.username) favs ocal_files inner join ocal_favs on ocal_favs.clipart_id = ocal_files.id group ocal_files.id order favs desc (instead of username should user_id, because have table users)
ocal_files has 37457 rows , ocal_favs has 18263
edit result of explain
mysql> explain select ocal_files.*, count(distinct ocal_favs.username) favs ocal_files inner join ocal_favs on ocal_favs.clipart_i d = ocal_files.id group ocal_files.id order favs desc; +----+-------------+------------+--------+----------------+---------+---------+---------------------------------+-------+---------------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | | +----+-------------+------------+--------+----------------+---------+---------+---------------------------------+-------+---------------------------------+ | 1 | simple | ocal_favs | | rlb_clipart_id | null | null | null | 18622 | using temporary; using filesort| | 1 | simple | ocal_files | eq_ref | primary | primary | 4 | openclipart.ocal_favs.clipart_id | 1 | using | +----+-------------+------------+--------+----------------+---------+---------+---------------------------------+-------+---------------------------------+ 2 rows in set (0.00 sec) why slow? can optimized? if yes how?
try create index on
ocal_favs ( clipart_id, username ) and make sure there not null constraint on ocal_favs.username or add ocal_favs.username not null condition.
this should allow information ocal_files , index.
Comments
Post a Comment