Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

aggregate function

Status
Not open for further replies.

flyadvertising

Programmer
Feb 5, 2011
8
US
The query (B) below is working, but in the first LEFT JOIN I'd like to pull the most recent result. So, I'd have to add something like the query (A) below in somehow.

A
SELECT poArID, poDatetime FROM posts ORDER BY poDatetime DESC

B
SELECT articles.arID, articles.arType, articles.arTitle, articles.arDescr, articles.arCl, articles.arURL, posts.poTxt, posts.poDatetime, posts.poAd, posts.poArID, advisors.adLname, advisors.adID, advisors.adFname, advisors.adTitle
FROM articles
LEFT JOIN posts ON articles.arID = posts.poArID
LEFT JOIN advisors ON posts.poAd = advisors.adID
WHERE arCl = '" . $clID . "'
GROUP BY articles.arTitle
ORDER BY articles.arTitle ASC ";
 
Code:
SELECT articles.arID
     , articles.arType
     , articles.arTitle
     , articles.arDescr
     , articles.arCl
     , articles.arURL
     , posts.poTxt
     , posts.poDatetime
     , posts.poAd
     , posts.poArID
     , advisors.adLname
     , advisors.adID
     , advisors.adFname
     , advisors.adTitle
  FROM articles 
[red]LEFT OUTER
  JOIN ( SELECT poArID
              , MAX(poDatetime) AS latest
           FROM posts 
         GROUP
             BY poArID ) AS m
    ON m.poArID = articles.arID[/red]
LEFT OUTER
  JOIN posts 
    ON posts.poArID = articles.arID
   [red]AND posts.poDatetime = m.latest[/red]
LEFT OUTER
  JOIN advisors 
    ON advisors.adID = posts.poAd
 WHERE articles.arCl = ". $clID ." [blue]-- no single quotes[/blue]
GROUP 
    BY articles.arTitle 
ORDER 
    BY articles.arTitle ASC


r937.com | rudy.ca
Buy my new book Simply SQL from Amazon
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top