9

I have three tables - node, content_type_product and share_content. There may be a 1:N relationship beetween node and share_content. I want to pull out only one record per id. If there is multiple records in share_content, I want the latest one, that is the highest value of sc.auto_id

SELECT sc.uid, n.uid, n.nid, sc.message 
  FROM node n 
    LEFT JOIN content_type_product p ON n.nid = p.nid 
    LEFT JOIN share_content sc ON n.nid = sc.nid 
  WHERE n.nid = 40513 
  GROUP BY sc.nid
  ORDER BY sc.auto_id
outis
  • 75,655
  • 22
  • 151
  • 221
sonofthom
  • 105
  • 1
  • 1
  • 6
  • You can use ORDER BY sc.auto_id DESC – Alex M Jan 05 '12 at 02:32
  • 1
    The [example](http://sscce.org/) is incomplete without schema (as `CREATE TABLE` statements), sample data (as `INSERT` statements) and desired results for the sample data. – outis Jan 05 '12 at 02:37
  • possible duplicate of [Select Rows with Maximum Column Value group by Another Column](http://stackoverflow.com/questions/1425240/), [How To Find The Top String Column Value in a Grouped Query](http://stackoverflow.com/questions/1443979/), [SQL Group by & Max](http://stackoverflow.com/questions/1299556/) – outis Jan 05 '12 at 02:40
  • ... [How can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL?](http://stackoverflow.com/questions/612231/), [Fetch the row which has the Max value for a column](http://stackoverflow.com/questions/121387/), and many, many others. – outis Jan 05 '12 at 02:51
  • "may be a 1:N relationship" -- a.k.a. 1:0..M correspondence ("one to zero or more"). – onedaywhen Jan 05 '12 at 09:11

2 Answers2

6

Why are you joining to content_type_product ?? But that aside, try

 SELECT c.uid, n.uid, n.nid, c.message  
 FROM node n  
   LEFT JOIN share_content c 
      ON c.nid = n.nid  
          And c.auto_id
             = (Select Max(auto_id)
                From share_content 
                Where nid = p.nid ) 
 Where n.nid = 40513  
 ORDER BY c.auto_id
Charles Bretana
  • 143,358
  • 22
  • 150
  • 216
1

Try:

SELECT sc.uid, n.uid, n.nid, sc.message FROM node n left join content_type_product p on n.nid = p.nid LEFT JOIN share_content sc on n.nid = sc.nid 
WHERE n.nid = 40513 
GROUP BY sc.nid, sc.auto_id
ORDER BY sc.auto_id DESC
Petar Sabev
  • 848
  • 6
  • 12