简体   繁体   中英

Laravel get n results per group

I have two tables : tbl_properties and tbl_property_images. I need to select latest 3 images of each property along with property_id . I tried with sub query with limit

DB::table('properties as p')
->leftjoin(DB::raw("(select property_id, property_image_id, image
                     from tbl_property_image 
                     where property_image_status = 1 
                     group by  property_id 
                     having count(*) = 3)  as tbl_imgtemp") , 'imgtemp.property_id', '=', 'p.property_id')
->where('property_status',1)
->get();

This returns total 3 records. please help me how can i do that. How can I select 3 images per property?

You use following query to get 3 images per property, I have used id column of images table to pick latest images assuming id column is set as auto increment

SELECT p.*,i.*
FROM properties  p
JOIN(SELECT i1.property_id,i1.property_image_status,i1.image
    FROM tbl_property_image i1 
    LEFT OUTER JOIN tbl_property_image i2
      ON (i1.property_id = i2.property_id AND i1.property_image_id < i2.property_image_id)
      WHERE i1.property_image_status = 1
    GROUP BY i1.property_id,i1.property_image_status,i1.image
    HAVING COUNT(*) < 3
) i
ON p.property_id = i.property_id

DEMO

Another approach using group_concat() if you need only a single column from images table

SELECT p.property_id , p.title,SUBSTRING_INDEX(GROUP_CONCAT(i.image ORDER BY i.property_image_id DESC),',',3) images
FROM properties  p
JOIN tbl_property_image i ON p.property_id = i.property_id
WHERE i.property_image_status = 1
GROUP BY p.property_id , p.title

But this solution has some limitations, As per docs The result is truncated to the maximum length that is given by the group_concat_max_len system variable, which has a default value of 1024. The value can be set higher, although the effective maximum length of the return value is constrained by the value of max_allowed_packet

DEMO

I have used sample schema and data set for above queries you have to adjust these as per your needs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM