Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select a single record in a left join

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, however, has several blurbs of content for each model. I need to select just the first blurb.

My tables look like this:

 Models // table  ModelID // pk  Model // varchar   Models_Content // table  ContentID // pk  ModelID // fk  Content // varchar   SELECT M.ModelID, M.Model, C.Content  FROM   Models M LEFT JOIN Models_Content C ON M.ModelID =  C.ModelID  WHERE      M.ModelID = 5 

How do I adjust my query to select just the very first blurb of content for a specific model?

like image 206
Evik James Avatar asked Sep 09 '11 15:09

Evik James


People also ask

How do I SELECT a single record from a table?

To return only the first row that matches your SELECT query, you need to add the LIMIT clause to your SELECT statement. The LIMIT clause is used to control the number of rows returned by your query.

Can you filter in a left join?

When doing a left join in SQL any filtering of the table after the join will turn it into an inner join. However there are some easy ways to do the filtering first. Suppose you've got some tables related to a website. The pages table describes the different pages on the site.


2 Answers

 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 
like image 122
MatBailie Avatar answered Sep 28 '22 09:09

MatBailie


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   
like image 20
Martin Smith Avatar answered Sep 28 '22 10:09

Martin Smith