LEFT OUTER JOIN,左表没有重复项

时间:2009-08-17 16:07:21

标签: mysql join

我有两张桌子(让我们说“左”和“右”表)。右表从无表到几行与左表的每一行相匹配。

我需要执行一个查询,我可以像LEFT OUTER JOIN一样工作加入这两个表,但是左表中每个现有的只能获得一行。该行应该是与右表中最高id相对应的行。

自然JOIN可以工作,但我不会从左表中获得与右边的任何行不匹配的行。

4 个答案:

答案 0 :(得分:4)

试试这个:

 Select L.[ValuesfromLeftTable], ...
        R.[ValuesfromRightTable], ...
 From LeftTable as L
   Left Join RightTable as R
     On R.Id = (Select Max(id) 
                From RightTable
                Where FK = L.Id)

答案 1 :(得分:2)

这就是我要做的事情:

select * 
  from `left` as l 
    LEFT JOIN `right` as r 
       on (l.id = r.left_id) 
group by l.id 
order by r.id

答案 2 :(得分:1)

您可以使用GROUP BY子句仅显示不同的记录

答案 3 :(得分:0)

SELECT Left.Field1, Left.Field2, ... Right.Field1, Right.Field2, ...
FROM tblLeft AS Left
LEFT JOIN (SELECT CommonID, Max([ID]) AS MaxID
    FROM tblRight
    GROUP BY CommonID) AS RightMax ON Left.CommonID = RightMax.CommonID
LEFT JOIN tblRight AS Right ON RightMax.MaxID = Right.[ID] AND Left.CommonID = Right.CommonID