This query is running very slow; it used to be 3 separate queries but I've consolidated it into 1. I assume it's slow because of the subselects it's doing, but I assume there might be a better way to query for this info.
* Background:*
users
is just user accounts.
posts
is all the post content.
posts_int
is just 2 fields, postid and intid. This stores interest ID's for posts.
int_usr
is also just 2 fields, userid and intid. This stores interest ID's for users.
All of the "intid" field names are based on another table that simply has ids and names for each interest. This query returns all posts for this user that are relevant to their selected interests, stored in integers in int_usr
.
The query:
SELECT DISTINCT
users.first_name,
users.last_name,
posts.id,
posts.userid,
posts.comments,
posts.date,
posts.comment
FROM posts
LEFT JOIN users ON
posts.userid = users.id
LEFT JOIN posts_int ON
posts.id = posts_int.postid
WHERE
posts_int.intid IN (
SELECT DISTINCT
intid
FROM int_usr
WHERE
intid IN (
SELECT DISTINCT
intid
FROM int_usr
WHERE
userid = '1'
)
ORDER BY intid ASC
)
AND posts.deleted = '0'
AND users.deleted = '0'
ORDER BY
posts.id DESC
LIMIT 0,12
Any help is appreciated!
Ryan
EDIT: Here is the explain you requested:
* EXPLAIN SQL: *
+----+--------------------+-----------+--------+----------------+---------+---------+---------------------------+------+----------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+--------------------+-----------+--------+----------------+---------+---------+---------------------------+------+----------------------------------------------+
| 1 | PRIMARY | posts_int | ALL | postid | NULL | NULL | NULL | 87 | Using where; Using temporary; Using filesort |
| 1 | PRIMARY | posts | eq_ref | PRIMARY,userid | PRIMARY | 4 | bunchify.posts_int.postid | 1 | Using where |
| 1 | PRIMARY | users | eq_ref | PRIMARY | PRIMARY | 4 | bunchify.posts.userid | 1 | Using where |
| 2 | DEPENDENT SUBQUERY | int_usr | ALL | NULL | NULL | NULL | NULL | 288 | Using where; Using temporary |
| 3 | DEPENDENT SUBQUERY | int_usr | ref | userid | userid | 4 | const | 19 | Using where; Using temporary |
+----+--------------------+-----------+--------+----------------+---------+---------+---------------------------+------+----------------------------------------------+
5 rows in set (0.00 sec)