How to select a single record in a left join
SELECT TOP 1 M.ModelID, M.Model, C.Content
FROM Models M LEFT JOIN Models_Content C ON M.ModelID = C.ModelID
WHERE M.ModelID = 5
ORDER BY C.ContentID ASC
Sean's answer is the best specific solution but just to add another "generalised" solution
SELECT M.ModelID,
M.Model,
C.Content
FROM Models M
OUTER APPLY (SELECT TOP 1 *
FROM Models_Content C
WHERE M.ModelID = C.ModelID
ORDER BY C.ContentID ASC) C
WHERE M.ModelID = 5
Change your JOIN
to:
LEFT JOIN (SELECT ModelID, MAX(Content) as Content FROM Models_Content GROUP BY ModelID)
This is assuming you don't care which Content
you get.
SELECT
M.ModelID, M.Model, C.Content
FROM
Models M
LEFT JOIN
Models_Content C
ON C.ContentID = (SELECT MIN(ContentID) FROM Models_Content WHERE ModelID = M.ModelID)
WHERE
M.ModelID = 5
Or
;WITH sorted_content AS
(
SELECT
ROW_NUMBER() OVER (PARTITION BY ModelID ORDER BY ContentID) AS itemID,
*
FROM
Models_Content
)
SELECT
M.ModelID, M.Model, C.Content
FROM
Models M
LEFT JOIN
sorted_content C
ON C.ModelID = M.ModelID
AND C.itemID = 1
WHERE
M.ModelID = 5