Question

I have two tables product and gallery. Each product can have multiple images in gallery. When I try to get LIMITed 5 products along with their gallery records, I do a JOIN like:

SELECT * FROM `product` p LEFT JOIN `gallery` g ON p.product_id = g.product_id 
LIMIT 0,5

This query returns me 5 records (i.e. only 3 products) like:

product_id   name   image
1            p1     im1.jpg
1            p1     im3.jpg
1            p1     xyz.jpg
2            p2     abc.jpg
3            p3     tuy.jpg

What I need is exactly 5 products, no matter how many gallery records against each product are and no matter how many total records be. Here's my expected result:

product_id   name   image
1            p1     im1.jpg
1            p1     im3.jpg
1            p1     xyz.jpg
2            p2     abc.jpg
3            p3     tuy.jpg
4            p4     a32.jpg
4            p4     t22.jpg
4            p4     a13c.jpg
5            p5     t34y.jpg

How can I do this via a single query?

Was it helpful?

Solution

Try this you can select the 5 products by subquery and join with images so you will get the records for 5 products,no matter how many images each product have

SELECT * FROM
 `gallery` g
INNER JOIN 
(SELECT * FROM  `product` LIMIT 5) p
 ON( p.product_id = g.product_id )

OTHER TIPS

You can modify your query like this,

SELECT * FROM `product` p LEFT JOIN (SELECT * FROM `gallery` LIMIT 0,5) as g ON    p.product_id = g.product_id 

But, using sub-query cost your performance.

To get five images for each product (which is a misinterpretation of the question):

SELECT *
FROM `product` p LEFT JOIN
     `gallery` g
     ON p.product_id = g.product_id 
WHERE 5 <= (select count(*)
            from gallery g2
            where g2.product_id = g.product_id and g2.image <= g.image
           );

An alternative way is to put the images into one comma separated column:

select p.*, substring_index(group_concat(distinct image), ',', 5) as images
from product p left join
     gallery g
     on p.product_id = g.product_id
group by p.product_id;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top