sql left join + one to many relationship

时间:2012-01-05 02:29:37

标签: sql left-join

我有三个表 - node,content_type_product和share_content。 可能是节点和share_content之间的1:N关系。我想每个id只能输出一条记录。 如果share_content中有多条记录,我想要最新的记录,即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

2 个答案:

答案 0 :(得分:5)

为什么要加入content_type_product? 但除此之外,请尝试

 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

答案 1 :(得分:1)

尝试:

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