Search code examples
mysqlinnodb

InnoDB has index problems when using COUNT() + WHERE


Recently, we switched from MyISAM to InnoDB. I tested the whole application and there are generally no problems except for one thing - using COUNT(*) in combination with 2 or more WHERE conditions.

So, here's the problem. The query below takes half a second which is not acceptable. After all InnoDB shouldn't be slower than MyISAM when using COUNT() + WHERE, but that's exactly what is happening here.

Both project_id and status_id are indexed columns. The table has 350K records.

SELECT COUNT(*) FROM respondents WHERE project_id='366' AND status_id='42'

And here is what EXPLAIN says:

id  select_type     table        type         possible_keys         key                   key_len   ref     rows    Extra   
1   SIMPLE          respondents  index_merge  project_id,status_id  project_id,status_id  4,1       NULL    8343    Using intersect(project_id,status_id); Using where...

When I use only one condition after WHERE (either project_id='366' or status_id='42'), it works fine. I'm thinking, this whole intersecting thing could be the root of the problem. But then what can I do about it? What do you think?


Solution

  • The index merge can be fixed by a compound index

    ALTER TABLE respondents ADD KEY(project_id,status_id)
    

    Assuming the data distribution is not very skewed,so this index will be useful.(the project_id='366' AND status_id='42' will not return more than 50% of rows)

    Also make sure that your column types match the search.Are project_id and status_id really VARCHAR? If not remove the quotes.