tags:

views:

420

answers:

4

I've got two tables (let's say "left" and "right" tables). The right table's got from none to several rows matching each row on the left table.

I need to perform a query where I can join the two tables the same way a LEFT OUTER JOIN works, but getting only one row for each existing one in the left table. That row should be the one corresponding to the highest id on the right table.

A NATURAL JOIN would work, but I won't be getting the rows from the left table that don't match any row on the right one.

+2  A: 

You can use GROUP BY clause to show only distinct records

Michael D.
A: 

This is what I would do:

select * 
  from `left` as l 
    LEFT JOIN `right` as r 
       on (l.id = r.left_id) 
group by l.id 
order by r.id
Dooltaz
This doesn't like it would work to me. Where's the bit to get the highest id? And the Group By will complain unless every column is specified in the Group By.
CodeByMoonlight
Edited to re-format so as to eliminate hor scrolling
Charles Bretana
This will not work, Select * will attempt to output all columns in both tables, all columns other than L.Id will cause error cause they are not in Group By clause.
Charles Bretana
+2  A: 

Try this:

 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)
Charles Bretana
Looks like a good answer.
Kirk Broadhurst
A: 
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
CodeByMoonlight