My problem is more clear on this post: Select all categories with latest post, user, and topic information
——————————————————————————————————————————
I have a query that pulls a list of the categories for my forum along with the latest post in that category. The results come back as expected, except that sub_post information being pulled in the LEFT JOIN fp1 changes if if run the query several times.
I first noticed this problem when viewing my webpage and refreshing several times. The post that it is pulling fluctuates between 3 posts. I'm not sure how this is even possible, unless there is something wrong with the query.
Please, take a look at my query below and let me know if there is something I am doing wrong that might explain this odd behavior.
Cheers.
SELECT fc1.id AS cat_id, fc1.cat_name AS cat_name,
fc1.cat_description AS cat_description, fc1.cat_views as cat_views, fp1.*
FROM forum_categories as fc1
LEFT JOIN (SELECT fp2.id AS sub_post_id,
fp2.post_date as sub_post_date,
fp2.post_topic as sub_post_topic,
u2.id as sub_user_id, u2.username as sub_username,
ft2.topic_subject as sub_topic_subject, ft2.topic_cat as sub_topic_cat
FROM forum_posts as fp2
LEFT JOIN users as u2 on fp2.post_by = u2.id
LEFT JOIN forum_topics as ft2 on ft2.id = fp2.post_topic
LEFT JOIN forum_categories as fcats on fcats.id = ft2.topic_cat
ORDER BY fp2.id DESC)
as fp1 on fp1.sub_topic_cat = fc1.id
GROUP BY fc1.id;
EXPLAIN SELECT:
+----+-------------+------------+--------+-------------------------+-------------+---------+--------------------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+------------+--------+-------------------------+-------------+---------+--------------------+------+-------------+
| 1 | PRIMARY | fc1 | index | PRIMARY,cat_name_unique | PRIMARY | 8 | NULL | 3 | Using where |
| 1 | PRIMARY | <derived2> | ref | <auto_key0> | <auto_key0> | 9 | tpw.fc1.id | 9 | NULL |
| 2 | DERIVED | fp2 | index | NULL | PRIMARY | 8 | NULL | 92 | NULL |
| 2 | DERIVED | u2 | eq_ref | PRIMARY | PRIMARY | 8 | tpw.fp2.post_by | 1 | NULL |
| 2 | DERIVED | ft2 | eq_ref | PRIMARY | PRIMARY | 8 | tpw.fp2.post_topic | 1 | NULL |
| 2 | DERIVED | fcats | eq_ref | PRIMARY | PRIMARY | 8 | tpw.ft2.topic_cat | 1 | Using index |
+----+-------------+------------+--------+-------------------------+-------------+---------+--------------------+------+-------------+
I have 3 tables: forums_categories, forums_topics, and forums_posts. I am trying to list the categories along with the latest post in that category. The forums_post is linked to forums_topics by a post_topic and the forums_topics is linked to the forums_categories with a topic_cat.