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.
3
Answers
You could actually implement this as a join with exists logic:
In plain English, this says to select every product image record having the smallest
pImageID
for each group ofproductID
records.One opption is to use ROW_NUMBER() analytic function like here:
One option is to get the earliest imageID for each product, then join this dataset with images and products tables to ensure only products with images are included :