Somewhat Complex MySQL Statement
I am creating a forum, and have gotten stuck creating the page that will display all the topics for a given forum. The three relevant tables & fields are structured as follows:
Table: forums_topics Table: forums_posts Table: users
-------------------- ------------------- ------------
int id int id int id
int forum_id int topic_id varchar name
int creator int poster
tinyint sticky varchar subject
timestamp posted_on
I've started with the following SQL:
SELECT t.id,
t.sticky,
u.name AS creator,
p.subject,
COUNT(p.id) AS posts,
MAX(p.posted_on) AS last_post
FROM forums_topics AS t
JOIN users AS u
LEFT JOIN forums_posts AS p ON p.topic_id = t.id
WHERE t.forum_id = 1
AND u.id = t.creator
GROUP BY t.id
ORDER B开发者_开发问答Y t.sticky
This appears to be getting me what I want (topic's id number, if its a sticky, who made the topic, the subject of the topic, number of posts for each topic, and timestamp of latest post). If there is a mistake though please let me know.
What I am having trouble with now is how I can add to this to get the name of the lastest poster. Can someone explain how I would edit my SQL to do that? I can provide more details if needed, or restructure my tables if that will make it simpler.
Here is a simple way to do this:
SELECT t.id,
t.sticky,
u.name AS creator,
p.subject,
COUNT(p.id) AS posts,
MAX(p.posted_on) AS last_post,
(SELECT name FROM users
JOIN forums_posts ON forums_posts.poster = users.id
WHERE forums_posts.id = MAX(p.id)) AS LastPoster
FROM forums_topics AS t
JOIN users AS u
LEFT JOIN forums_posts AS p ON p.topic_id = t.id
WHERE t.forum_id = 1
AND u.id = t.creator
GROUP BY t.id
ORDER BY t.sticky
Basically, you do a sub-query to find the user based upon the max id. If your IDs are GUIDs or are not in order for some other reason, you could do the lookup based upon the posted_on timestamp instead.
精彩评论