Hi there,
I have this MySQL query, which pulls the 7 most recent posts from the forums:
SELECT p.*, u.username, u.session_active, u.profile_snippet, t.topic_title
FROM forums_posts p
INNER JOIN users u
ON p.user_id = u.id
INNER JOIN forums_topics t
ON p.topic_id = t.topic_id
ORDER BY p.post_id DESC
LIMIT 7
Takes about ~7.5 seconds to execute… which is awfully slow.
An EXPLAIN reveals:
+----+-------------+-------+--------+------------------+----------+---------+--------------------------+-------+---------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+--------+------------------+----------+---------+--------------------------+-------+---------------------------------+
| 1 | SIMPLE | t | ALL | PRIMARY | NULL | NULL | NULL | 34328 | Using temporary; Using filesort |
| 1 | SIMPLE | p | ref | user_id,topic_id | topic_id | 8 | -------------.t.topic_id | 21 | |
| 1 | SIMPLE | u | eq_ref | PRIMARY | PRIMARY | 8 | -------------.p.user_id | 1 | |
+----+-------------+-------+--------+------------------+----------+---------+--------------------------+-------+---------------------------------+
SHOW INDEXES FROM forums_posts:
Table Non_unique Key_name Seq_in_index Column_name Collation Cardinality Sub_part Packed Null Index_type Comment
forums_posts 0 PRIMARY 1 post_id A 851538 NULL NULL BTREE
forums_posts 1 user_id 1 user_id A 1896 NULL NULL BTREE
forums_posts 1 topic_id 1 topic_id A 77412 NULL NULL BTREE
SHOW INDEXES FROM forums_topics:
Table Non_unique Key_name Seq_in_index Column_name Collation Cardinality Sub_part Packed Null Index_type Comment
forums_topics 0 PRIMARY 1 topic_id A 34140 NULL NULL BTREE
forums_topics 1 forum_id 1 forum_id A 27 NULL NULL BTREE
Any ideas as to how to optimize this query so it’s not so slow? I think I’m missing something or have an improper index strategy. Thanks in advanced.