Get count matches in query on large table very slow

Posted by Roy Roes on Stack Overflow See other posts from Stack Overflow or by Roy Roes
Published on 2011-01-12T21:35:19Z Indexed on 2011/01/12 21:53 UTC
Read the original article Hit count: 161

Filed under:
|
|

I have a mysql table "items" with 2 integer fields: seid and tiid
The table has about 35000000 records, so it's very large.

seid  tiid  
-----------
1     1  
2     2  
2     3  
2     4  
3     4  
4     1  
4     2

The table has a primary key on both fields, an index on seid and an index on tiid.

Someone types in 1 or more tiid values and now I would like to get the seid with most results.

For example when someone types 1,2,3, I would like to get seid 2 and 4 as result. They both have 2 matches on the tiid values.

My query so far:

SELECT COUNT(*) as c, seid
  FROM items
 WHERE tiid IN (1,2,3) 
GROUP BY seid
HAVING c = (SELECT COUNT(*) as c, seid
              FROM items
             WHERE tiid IN (1,2,3) 
          GROUP BY seid
          ORDER BY c DESC 
             LIMIT 1)

But this query is extremly slow, because of the large table.

Does anyone know how to construct a better query for this purpose?

© Stack Overflow or respective owner

Related posts about sql

Related posts about mysql