I have the below query to optimize.
SELECT count(*) AS count FROM area
INNER JOIN entity ON area.id = entity.id
INNER JOIN areacust ON area.id = areacust.id
WHERE entity.deleted=0
AND area.id > 0
There are indexes on deleted, ids on all the tables.
Now when i have suppose 20 Lac (2 million) of records then the query takes lots of time to give me the result. Its between 10 to 20 seconds.
How can i optimize it more. Also is there any other technique to get count.
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE vtiger_crmentity ref PRIMARY,entity_deleted_idx entity_deleted_idx 4 const 729726 Using where; Using index
1 SIMPLE area eq_ref PRIMARY PRIMARY 4 area.id 1 Using index
1 SIMPLE areacust eq_ref PRIMARY PRIMARY 4 area.id 1 Using where; Using index
New explain for composite key
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE entity ref PRIMARY,entity_deleted_idx,comp_index deleted_idx 4 const 928304 Using index
1 SIMPLE area eq_ref PRIMARY PRIMARY 4 entity.id 1 Using index
1 SIMPLE areacust eq_ref PRIMARY PRIMARY 4 entity.idid 1 Using index
EXPLAINplan of your queryFROM area FORCE INDEX (area.id)COUNT(*).. if you want to count only things in one table you could docount(a.id)or even(a.*).. but that would only matter if there wereLEFT JOINSthat caused there to be additional rows... MySQL performs almost identically forCOUNT(ID)orCOUNT(*).. except when there arenullvalues to be counted... if there are null values you should ALWAYS useCOUNT(*)because MySQL knows how to handle it better that way.. cuts the execution time in half.