views:

33

answers:

2

I'm trying to execute the following query

SELECT * FROM person 
         WHERE id IN 
             ( SELECT user_id FROM participation 
                    WHERE activity_id = '1' AND application_id = '1' 
             )

The outer query returns about 4000 responses whilst the inner returns 29. When executed on my web server nothing happened and when I tested it locally mysql ended up using 100% CPU and still achieved nothing. Could the size be the cause?

Specifically it causes the server to hang forever, I'm fairly sure the web server I ran the query on is in the process of crashing due to it (woops).

+2  A: 

why don't you use an inner join for this query? i think that would be faster (and easier to read) - and maybe it solves your problem (but i can't find a failure in your query).

EDIT: the inner-join-solution would look like this:

SELECT
  person.*
FROM
  person
INNER JOIN
  participation
ON
  person.id = participation.user_id
WHERE
  participation.activity_id = '1'
AND
  participation.application_id = '1'
oezi
Subquery is executed for each row of the main query, so JOIN is a proper and much faster approach.
Naktibalda
@Naktibalda, are you sure? That wasn't my understanding of how a subquery worked. I am almost positive that a temporary table is created so it's only executed once.
Mike Sherov
Thanks oezi, I'll give it a go if/when the server comes up again haha.
Chris
@oezi - Do not use or recommend the comma syntax. Use the proper ANSI INNER JOIN format.
Thomas
@Thomas - thanks for the hint, i changed that.
oezi
+1  A: 

How many rows are there in participation table and what indexes are there? A multi-column index on (user_id, activity_id, application_id) could help here.

Re comments: IN isn't slow. Subqueries within IN can be slow, if they're correlated to outer query.

Mchl