Question

product table in SQL tables:

Product: 
    ID,
    Name

ProductImage
    ID,
    ProductID,
    Image

I want to select an image in select query of Product I need first/last image of product1, first/last image of product2, etc

Something like:

select Product.id,Product.name,(select top(1)image from productimage where productimage.ProductID=product.ID)as Image from product
Was it helpful?

Solution

Try this,Maybe useful:

select Product.id,Product.name,
(select top (1) image from productimage where productimage.ProductID=product.ID order by productimage.ID asc)as FirstImage ,
(select top (1) image from productimage where productimage.ProductID=product.ID order by productimage.ID desc) as LastImage
from product

OTHER TIPS

Temp Table subqueries are better for long run over column level subqueries.

Ex:

SELECT
    Product.id,
    Product.name,
    productImageTable.Image AS Image 
FROM Product INNER JOIN
(SELECT 
    ProductID,
    Min(image) as Image 
FROM productimage 
GROUP BY ProductID) AS productImageTable ON 
    productImageTable.ProductID=Product.ID
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top