-1

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.

The Impaler
  • 30,269
  • 7
  • 28
  • 55

1 Answers1

2

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;
Gordon Linoff
  • 1,122,135
  • 50
  • 484
  • 624