如何在左连接中选择单个记录

时间:2011-09-09 15:24:20

标签: sql sql-server tsql sql-server-2008

我需要使用其关键的ModelID从Models表中选择一个特定的模型。我还需要从Model_Content表中添加一些内容。但是,Models_Content表对每个模型都有几个内容模糊。我需要选择第一个模糊。

我的表格如下:

 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

如何调整查询以仅选择特定模型的第一个内容模糊?

8 个答案:

答案 0 :(得分:43)

 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

或者

;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

答案 1 :(得分:9)

Sean的答案是最具体的解决方案,但只是添加另一个“通用”解决方案

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  

答案 2 :(得分:4)

 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

答案 3 :(得分:1)

将您的JOIN更改为:

LEFT JOIN (SELECT ModelID, MAX(Content) as Content FROM Models_Content GROUP BY ModelID)

这假设你不关心你得到哪个Content

答案 4 :(得分:0)

您可以选择MIN ( contentID )

答案 5 :(得分:0)

这可能是兰迪答案的扩展,但对我来说并不完全清楚。

出于性能原因,我希望尽量减少查询中SELECT个语句的数量,因此我在主要选择中使用了MIN语句而不是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

根据数据总量,可能需要权衡。 IDK。我的查询需要从删除了几个步骤的条件中挖掘出数据。

答案 6 :(得分:0)

MySQL 5.7+ 允许您使用 4 7 8 +ANY_VALUE 它将从连接表的一个(随机)行返回列。

GROUP BY

或者,万一您需要它用于所有型号

SELECT M.ModelID, M.Model, ANY_VALUE(C.Content)
FROM   Models M 
LEFT JOIN Models_Content C ON M.ModelID = C.ModelID
WHERE      M.ModelID = 5

更多信息:https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html

答案 7 :(得分:-1)

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