简体   繁体   中英

sql left join +one to many relationship

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM