简体   繁体   中英

Slow COUNT(*) Query takes longer than 1 second to execute, how can I make it faster?

I have the following query:

SELECT COUNT( * ) 
FROM Table1 AS T1
LEFT JOIN Table2 AS T2
USING ( col1 ) 
WHERE T1.col1 !=  '1'
AND T1.col2
IN (
'A',  'A-B'
)
AND T1.col3 =  'X'
AND T2.col11=  '1'
AND T1.col4 =  'YZ'

This query takes over 1 second to execute. If I replace COUNT(*) with SELECT(*) , it also takes over 1 second . However, if I then also add LIMIT 0,30 at the end, it executes in just 0.02 seconds .

I have an index on all columns in the WHERE clause. I even have a Composite Index in Table1 .

Below is the EXPLAIN EXTENDED of this query:

id  select_type table   type    possible_keys   key key_len ref rows    filtered    Extra
1   SIMPLE  T1  ref PRIMARY,col4,col3,col2,col1,CompositeIndex...   CompositeIndex1 2   const   2010    100 Using where
1   SIMPLE  T2  eq_ref  PRIMARY,CompositeIndex1,incomeLevel PRIMARY 4   T1.col1 1   100 Using where

Why is this query taking so long and how can I make it faster?

For starters you're using a LEFT join but requiring T2.col11= '1'

Beyond that, there's not enough information to comment, except to say I hope that you don't really number your columns.

Here is your original query

SELECT COUNT( * ) 
FROM Table1 AS T1
LEFT JOIN Table2 AS T2
USING ( col1 ) 
WHERE T1.col1 !=  '1'
AND T1.col2
IN (
'A',  'A-B'
)
AND T1.col3 =  'X'
AND T2.col11=  '1'
AND T1.col4 =  'YZ'

You need to do two things to speed this up

REFACTOR THE QUERY

Here is your refactored query

SELECT COUNT(T1.col1) FROM
(SELECT col1 FROM T1 WHERE col3='X' AND
col4='YZ' AND col2 IN ('A','A-B') AND col1<>'1') T1
INNER JOIN (SELECT col1 FROM T2 WHERE T2.col11='1') T2
USING (col1);

ADD INDEXES TO SUPPORT THE SUBQUERIES

ALTER TABLE T1 ADD INDEX col3421_index (col3,col4,col2,col1);
ALTER TABLE T2 ADD INDEX col11_1_index (col11,col1);

Give it a Try !!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM