I’m having a problem with a sql query to do the following:
I need to select all products from products table and for each product i need to join a main image (all columns) from images table. Product images table contains image-product relations and a column sortWeight. Main image is the one with the smallest sortWeight.
To get the main product image, i’d do this:
SELECT * FROM images WHERE product=SOME_PRODUCT ORDER BY sortWeight ASC LIMIT 1;
To get all products:
SELECT * FROM products;
Now i need to join these two somehow, but the problem is i don’t know how to bypass a limitation in the following:
SELECT P.* FROM products AS P
LEFT JOIN
(SELECT * FROM images AS I WHERE I.product=P.id ORDER BY sortWeight ASC LIMIT 1) AS I1
The problem is MySQL does not know what P.id is inside the subquery. I’ve also tried it like this:
SELECT P.* FROM products AS P
LEFT JOIN
(SELECT * FROM images AS I WHERE ORDER BY sortWeight ASC LIMIT 1) AS I1 ON (I1.product = P.id)
but i don’t think this gives an accurate result since there’s a limit in subquery and it may select the image from another product with smaller sortWeight.
Can anyone help me rewrite this? Thank you.
Try to join it to subquery that returns images with smallest (
min) sortWeight for eachproduct.This returns smallest sortWeight for each product:
this is combined version: