I need to select a specific model from the Models table using its key ModelID. I also need to add a blurb of content from the Model_Content table. The Models_Content table, howe
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
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.
you could select the MIN ( contentID )
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
This may be an expansion on Randy's answer, but it's not completely clear to me.
For performance reasons I wanted to minimize the number of SELECT
statements in my query, so I used a MIN
statement within the primary select instead of within the JOIN
:
SELECT
table_1.id AS id,
table_1.name AS name,
MIN(table_2.id) AS table_2_id
FROM table_1
LEFT JOIN table_2 ON table_2.table_1_id = table_1.id
-- additional JOINs and WHERE excluded
GROUP BY table_1.id, table_1.name
LIMIT 5
There may be tradeoffs depending on the total amount of data. IDK. My query needs to tunnel into the data from a condition several steps removed.
SELECT M.ModelID
, M.Model
, (SELECT TOP 1 Content
FROM Models_Content
WHERE ModelID = M.ModelID
ORDER BY ContentId ASC) as Content
FROM Models M
WHERE M.ModelID = 5