Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql left join +one to many relationship

Tags:

sql

left-join

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
like image 210
sonofthom Avatar asked Jan 05 '12 02:01

sonofthom


2 Answers

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
like image 129
Charles Bretana Avatar answered Oct 08 '22 03:10

Charles Bretana


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
like image 29
Petar Sabev Avatar answered Oct 08 '22 01:10

Petar Sabev