Search code examples
sql-server-2008top-n

how to select one image of a object stored in another table


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

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