Question

I have BaseProducts, Images and ProductsImages(many to many) tables. I have this query,

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 

This works but it looks clumsy to me. Can I convert this into JOIN?

Was it helpful?

Solution

You could convert it to a join. But that would be uglier. In SQL Server, it is easier to express this using 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;

Doing this as a join would require using row_number() to extract the "first" image path.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top