Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql server top query

I don't know what's wrong with this query :

select * from products , top 1 * from pic 
where products.productId = pic.productId

I have Products and Pic tables , every products could have 1 to n pic and I would like to return every product and the first pic of that

The picture of diagram may help enter image description here

like image 647
Mostafa Avatar asked Sep 18 '26 14:09

Mostafa


1 Answers

You need to have a way of uniquely identifying each pic, so I'm asuming that table as an ID column...

SELECT
  *
FROM
  products
LEFT JOIN
  pic
    ON pic.Id = (SELECT TOP 1 id FROM pic WHERE productID = products.ProductID ORDER BY id DESC)


EDIT

Inspired by another answer, using APPLY instead...

SELECT
  *
FROM
  products
OUTER APPLY
  (SELECT TOP 1 * FROM pic WHERE productID = products.ProductID ORDER BY id DESC) AS pic
like image 150
MatBailie Avatar answered Sep 21 '26 04:09

MatBailie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!