简体   繁体   中英

MySQL - Query very slow

I have statements like this that are timing out:

SELECT COUNT(*) FROM A WHERE A.value1 IN (
  SELECT A.value1 FROM A WHERE A.value2 = 0
)

Table A has 13,000,000+ rows in it, and because of some reasons, I can't use indexes.

So how to speed it up without use indexes? I'm using MySQL 5.6.

Any help please.

I would first try using exists . This often optimizes better:

SELECT COUNT(*)
FROM A 
WHERE EXISTS (SELECT 1
              FROM A A2
              WHERE A2.value2 = 0 AND A2.value1 = A.value1
             );

The optimal index for this is A(value2, value1) .

You could also use two levels of aggregation:

select sum(cnt)
from (select value1, count(*) as cnt
      from a
      group by value1
      having sum(value2 = 0) > 0
     ) a;

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