When I isolate this query:
SELECT `Tagged`.`contact_id`
FROM contacts_tags AS Tagged LEFT JOIN tags AS Tag ON (`Tagged`.`tag_id` = `Tag`.`id`)
WHERE `Tag`.`id` = 137;
i get:
+------------+
| contact_id |
+------------+
| 3519 |
| 17080 |
+------------+
But when i combine it with a larger query using “IN” I get some sort of recursive loop and my database starts eating up processing power until it times out.
SELECT `Contact`.*
FROM `contacts` AS `Contact`
WHERE `Contact`.`id` in
(SELECT `Tagged`.`contact_id`
FROM contacts_tags AS Tagged LEFT JOIN tags AS Tag ON (`Tagged`.`tag_id` = `Tag`.`id`)
WHERE `Tag`.`id` = 137 );
This just keeps running until i reset the server.
But then It works when I list the first query response manually:
SELECT `Contact`.*
FROM `contacts` AS `Contact`
WHERE `Contact`.`id` in
(3519, 17080);
What is the difference?
The current GA release of MySQL is really bad at optimizing subequeries. Chances are that the subquery is being executed for each row in
Contacts. You can see this if you runEXPLAIN your_query_here. You’ll like see that the subquery has been taggedDEPENDENT SUBQUERY.It’s not a great solution, but something like this might work.
This should force MySQL to cache the subquery. Alternatively, if you know that query is going to return a small number of values, you might be better off simply performing two separate queries.