SQL How to join 2 tables with or without
Remove the additional unnecessary join to contact:
SELECT
Person.Id,
Person.Name,
GroupedContact.MaxDate as outputCol
FROM
Person
LEFT JOIN (
SELECT Contact.PersonId,
MAX(Contact.Date) AS MaxDate
FROM Contact
GROUP BY Contact.PersonId
) GroupedContact ON
Person.PersonId = GroupedContact.PersonId
A few notes: Never mix implicit and explicit joins. Always use explicit joins. You need here a LEFT
join which means -> keep all the records from the LEFT
tables and those that match from the RIGHT
table.
You need LEFT join instead of RIGHT and extra join to contacts is not needed:
SELECT
Person.Id,
Person.Name,
GroupedContact.MaxDate
FROM Person
LEFT JOIN
(
SELECT Contact.PersonId,
MAX(Contact.Date) AS MaxDate
FROM Contact
GROUP BY Contact.PersonId
) GroupedContact
ON Person.Id = GroupedContact.PersonId