简体   繁体   中英

Codeigniter join, group by and count a row from one table

I'm struggling a bit with this code to get the count result from book_listing (totally) which is the total count of bookings. From the result, some are correct but some are multiplied by 3 or so.

Here is my code:

$this->db->where('list_status', 1)
         ->where('list_date >=', date('Y-m-d'))
         ->order_by("user_listings.list_created", "desc")
         ->limit(18, null)
         ->select('*, COUNT(user_bookings.book_listing) as totally')
         ->from('user_listings')
         ->join('user_images', 'user_images.img_listing = user_listings.list_reference')
         ->join('user_states', 'user_states.state_id = user_listings.list_state')
         ->join('user_bookings', 'user_bookings.book_listing = user_listings.list_reference', 'left')
         ->group_by('user_listings.list_reference')
         ->get();

Thanks to any help :)

So I solved it, the user_images table seems to be causing the issue due to multiple images being fetched while I need it to return only one.

$this->db->where('list_status', 1)
         ->where('list_date >=', date('Y-m-d'))
         ->order_by("user_listings.list_created", "desc")
         ->limit(18, null)
         ->select('user_listings.*,image.*,user_states.*')
         ->select('COUNT(user_bookings.book_listing) as totalBooked')
         ->from('user_listings')
         ->join('user_bookings', 'user_bookings.book_listing = user_listings.list_reference', 'left')
         ->join('(SELECT * FROM user_images WHERE user_images.img_key IN(SELECT MIN(user_images.img_key) FROM user_images GROUP BY user_images.img_listing)) AS image',
                                            'image.img_listing = user_listings.list_reference')
         ->join('user_states', 'user_states.state_id = user_listings.list_state')
         ->group_by('user_listings.list_reference')
         ->get();

Basically, I had to do a select from the join table for user_images . Hope it helps someone else :)

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