SitePoint Sponsor

User Tag List

Results 1 to 2 of 2

Thread: Query Help

  1. #1
    SitePoint Evangelist FCC's Avatar
    Join Date
    May 2006
    Posts
    417
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Query Help

    Hi all,

    I am stumped on how to write query. My table scheme is:

    ThreadID | CommentID | CommentDate

    So the threadID is the priminary key and comments are added to threads. I want to sort the threadID by the most recent commentDate.

    So I figured the query:

    Code:
    SELECT ThreadID, CommentDate FROM Comments ORDER BY CommentDate
    This sorta works, but it just returns all the rows sorted by CommentID. I want the ThreadID to be unique and return the most recent comment of that thread.

    Any hints on how to do this?

  2. #2
    SQL Consultant gold trophysilver trophybronze trophy
    r937's Avatar
    Join Date
    Jul 2002
    Location
    Toronto, Canada
    Posts
    39,336
    Mentioned
    63 Post(s)
    Tagged
    3 Thread(s)
    Quote Originally Posted by FCC View Post
    I want the ThreadID to be unique and return the most recent comment of that thread.
    Code:
    SELECT ThreadID
         , CommentID 
         , CommentDate 
      FROM Comments as T
     WHERE CommentDate = 
           ( SELECT MAX(CommentID)
               FROM Comments
              WHERE ThreadID = T.ThreadID )
    ORDER 
        BY CommentDate
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL
    "giving out my real stuffs"


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •