Jump to content

Recommended Posts

I have a particular query that I'm wondering will work as I hope.  Could a helpful forum-goer take a look, please?

 

Let's say I'm trying to implement a forum, and I have a Forum table like so:

┌─────────────┐
│ Forum       │
│-------------│
│ ForumID     │
│ Title       │
│ Description │
└─────────────┘

 

And a Thread table like so:

┌─────────────┐
│ Thread      │
│-------------│
│ ThreadID    │
│ ForumID     │
│ Title       │
└─────────────┘

 

And finally a Post table like so:

┌─────────────┐
│ Post        │
│-------------│
│ PostID      │
│ ThreadID    │
│ User        │
│ DatePosted  │
└─────────────┘

With the obvious foreign-key relationships.

 

Now, I need a query that displays the threads in a particular forum reverse-sorted by date of a thread's most recent post.  The best way to do this would be if the rows returned also contained the columns from the post table for that most recent post.  I've gotten this far, but I'm not sure if the following query does what I want it to do.  Is there any guarantee that the following query will correctly select the most recent post in association with a distinct thread or just any post from that thread?  Also, since this query returns columns with the same name, will referencing that column in the PHP associative array have different or special behavior?

SELECT Thread.*, Post.*, DISTINCT Thread.ThreadID FROM Thread
INNER JOIN Post ON Thread.ThreadID = Post.PostID
WHERE Thread.ForumID='somegivenforumid'
ORDER BY Post.DatePosted DESC

 

If it matters any, I'm using MySQL 4.  Any help would be greatly appreciated!  Thank you beforehand :).

Link to comment
https://forums.phpfreaks.com/topic/84715-selection-query-help/
Share on other sites

SELECT f.Description, t.Title, MAX(p.DatePosted) as lastpost
FROM post p
    INNER JOIN thread t ON p.ThreadID = t.ThreadID
    INNER JOIN forum f ON t.ForumID = f.ForumID
WHERE t.ForumID = '$somegivenforumid'
GROUP BY f.Description, t.Title
ORDER BY lastpost DESC

Link to comment
https://forums.phpfreaks.com/topic/84715-selection-query-help/#findComment-432278
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.