If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Data Access, Manipulation & Batch Languages > ANSI SQL > Help with sorting results

Reply
 
LinkBack Thread Tools Display Modes
  #1 (permalink)  
Old 12-10-09, 16:03
JackBauer3 JackBauer3 is offline
Registered User
 
Join Date: Dec 2009
Posts: 2
Help with sorting results

Hi I need help with sql query to get results in correct order

I've two tables:
Topic [ idtopic, idforum, title, description, views]
Post [ idpost, idtopic, iduser, message, dateadded ]

I need to get data from Topic table that is sorted by post.dateadded. It's for topics listing page on forum so it works like: somebody adds reply to topic and in my query fetching all topics that row should go on top. I hope you understand what i mean.

This is what i managed to write
Code:
SELECT t.title, p.dateadded
FROM Topic AS t
JOIN Post AS p ON p.idtopic = t.idtopic
WHERE t.idforum =1
ORDER BY p.dateadded DESC
That is almost what i want but I need it to sort by max(p.dateadded) -> the last post from topic, not by all posts like it's now (There should be less results).
Reply With Quote
  #2 (permalink)  
Old 12-10-09, 16:22
r937 r937 is offline
SQL Consultant
 
Join Date: Apr 2002
Location: Toronto, Canada
Posts: 19,084
oops, see next post
__________________
r937.com | rudy.ca
please visit Simply SQL and buy my book
Reply With Quote
  #3 (permalink)  
Old 12-10-09, 16:23
r937 r937 is offline
SQL Consultant
 
Join Date: Apr 2002
Location: Toronto, Canada
Posts: 19,084
Code:
SELECT t.title
     , p.last_post
  FROM Topic AS t
INNER
  JOIN ( SELECT idtopic
              , MAX(dateadded) AS last_post
           FROM Post 
         GROUP
             BY idtopic ) AS p 
    ON p.idtopic = t.idtopic
 WHERE t.idforum =1
ORDER 
    BY p.last_post DESC
__________________
r937.com | rudy.ca
please visit Simply SQL and buy my book
Reply With Quote
  #4 (permalink)  
Old 12-10-09, 16:43
JackBauer3 JackBauer3 is offline
Registered User
 
Join Date: Dec 2009
Posts: 2
r937 thanks a lot it worked. Really appreciate your help!
Reply With Quote
Reply

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On