I am lookign for the correct SQL code to join 2 tables and show only the last record of the details table.
I have a DB with 2 tables,
Deals
Deal
Obligatory no-subquery-nowhere-answer:
select d.*
, dc.*
from Deals d
left outer join DealComments dc
on d.DealID = dc.DealID
left outer join DealComments dc1
on d.DealID = dc1.DealID
and
dc1.CommentTime > dc.CommentTime
where dc1.CommentTime is null
Show me everything in Deals
and DealComments
when there exists no CommentTime
greater than any given comment time for a particular DealID
.
Edit: as Alex Kuznetsov astutely points out in a comment: the OP requested that all deals be displayed -- whether a deal has a comment or not. So I have changed the first JOIN
from INNER
to LEFT OUTER
.