I have a bit complex mysql select query question.
I have 2 tables as shown in the image below. One is for products and the other one is the images of products. I can select the products with images with inner join.
But, since there are a lot of items in the "product images table", I want to select just one image from the table for each product.
and here is the desired result table :
It doesn't matter which image is retrieved from the images table but to make it less complex I can -for example- get the min(imageID) one.
I want to use this query to display products in my e-commerce page. I don't want to get all the images on page is loaded. So, just one image for each product is ok for me.
Thanks for any help.
You could actually implement this as a join with exists logic:
SELECT pImageID, productID, productImage
FROM productImages p1
WHERE NOT EXISTS (
SELECT 1
FROM productImages p2
WHERE p2.productID = p1.productID AND
p2.pImageID < p1.pImageID
);
In plain English, this says to select every product image record having the smallest pImageID
for each group of productID
records.