I have 2 tables, a product table and an image table. Products can have more than 1 image per record. I need an SQL statement that will list 1 image per product rather than all images per product.
A scaled down example of my current effort is:
SELECT Product.RefCode, Img.ImgPath
FROM Product INNER JOIN (
SELECT ProductImg.ImgPath, ProductImg.PrdFK
FROM ProductImg
LIMIT 0,1) AS Img ON Product.PrdID = Img.PrdFK;
The above example returns 0 results, however, if I remove the LIMIT 0,1 from the Sub SELECT I get a complete list of all products and all images.
I just want 1 image record per product record to be returned.
I have revised “a programmer” code to MySQL and it works fine.
SELECT Product.RefCode,
(Select ProductImg.ImgPath
From ProductImg
Where Product.PrdID = Img.PrdFK LIMIT 0,1) AS ImgPath
FROM Products
For some reason when trying “Bill Karwin’s” solution, it sent the server loading for a long time.
This should work:
If you have a way to determine which image should the select return, then you can add a where and maybe an Order By in the sub-select.
In the following example, we’ll get only the latest of the active images.
Edited and corrected ‘Top 1’ to ‘Limit 0,1’.