将子查询转换为LEFT Join?

时间:2014-05-01 13:50:49

标签: sql sql-server-2012

我有BaseProducts,Images和ProductsImages(多对多)表。我有这个问题,

SELECT BaseProducts.*, 
       (SELECT TOP 1 Images.[Path] 
        FROM   Images AS Images 
               INNER JOIN ProductsImages AS ProductsImages 
                       ON Images.Id = ProductsImages.ImageId 
        WHERE  ProductsImages.BaseProductId = BaseProducts.Id 
        ORDER  BY [ProductsImages].[Order]) AS ImagePath 
FROM   CTEPage AS BaseProducts 

这样可行,但对我来说看起来很笨拙。我可以将其转换为JOIN吗?

1 个答案:

答案 0 :(得分:2)

您可以将其转换为join。但那会更加丑陋。在SQL Server中,使用apply表达它更容易:

SELECT BaseProducts.*
       i.ImagePath, AS ImagePath
FROM CTEPage BaseProducts OUTER APPLY
     (SELECT TOP 1 Images.[Path] as ImagePath
      FROM Images i INNER JOIN
           ProductsImages pi
           ON i.Id = pi.ImageId
      WHERE pi.BaseProductId = BaseProducts.Id
      ORDER BY [ProductsImages].[Order]
     ) i;

join执行此操作需要使用row_number()来提取“第一个”图像路径。