Jump to content

group by & order by


PRSBOY

Recommended Posts

Hey there,

 

I'm trying to whip up some forums, only basic and secure. Here are my involved tables:

 

forumthread

threadid 	 	 
threadviews	 
groupid	 
forumid 	 
threadtitle	 
threadsticky 	 
userid

 

threadid is the primary key, auto_inc.

 

forumpost

postid 	 
threadid	 	 
forumid 	 
userid 	 	 
groupid	 	 
postbody 	 
postdate

 

postid is the primary key, auto_inc.

threadid is the foreign key linking to a specific thread.

 

What I am trying to do, is print the each thread, listing its number of replies (count(postid)), last poster details (ORDER BY forumpost.postdate DESC)

 

The SQL I has was:

SELECT
p.*
t.*
FROM forumpost p
LEFT JOIN forumthread t ON p.threadid = t.threadid
GROUP BY p.threadid
ORDER BY p.postdate DESC

 

The problem is: the query selects the correct number of rows, however, it does not return the correct data for the last poster.

 

I'm really in need of some help, if you need any more info just let me know.

 

Cheers!

Link to comment
https://forums.phpfreaks.com/topic/152922-group-by-order-by/
Share on other sites

sorry, I missed out the where clause!

 

should be:

 

WHERE t.forumid = $forumid

 

I'm getting all threads/posts that are in a certain forum (e.g. $forumid = 2).

 

There is what i'd like to do:

Step 1: Get all threads from forumthread (there is no postdate here, so I cant order by postdate to get them in the correct order

Step 2: Join forumpost on forumthread.threadid = forumpost.threadid, then order all of the data on forumpost.postdate so that the thread with the latest post is at the top, then in order of last postdate (DESC)

 

That should make it more clear, thank you for your reply!

Link to comment
https://forums.phpfreaks.com/topic/152922-group-by-order-by/#findComment-803381
Share on other sites

I have 3 rows in forumthread - therefore I've made three posts.

I have 7 rows in forumpost - therefore I have made 4 replies (7-3).

 

Nope, that's not working - I changed some parts of the query but it still returns 1 row, and it does not order it correctly.

 

What I was trying to do was to group by threadid then order that group on postdate DESC.

Link to comment
https://forums.phpfreaks.com/topic/152922-group-by-order-by/#findComment-803426
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.