简体   繁体   中英

Retrieve one record for each column irrespective of number records in the table

I want to select one record with two joins. I have following query:

$this->db
        ->select('vehicle.idvehicle, vehicle.mark, vehicle.model, vehicle.type, vehicle.author_id, users.nick, photos.name')
        ->from('xxxxxsld_auto.vehicle')
        ->join('users', 'vehicle.author_id = users.userid')
        ->join('photos', 'vehicle.idvehicle = photos.vehicle_id')
        ->get()
        ->result_array();

It works fine, but if I have more photos in DB, I get more more records, it depends of photos record. What should I do to receive one record for each vehicle irrespective of number record in photos table?

Edit: LIMIT and DISTINCT didn't work.

You can use GROUP_CONCAT and SUBSTRING_INDEX to pick one photo, if you want all the photos you can just use GROUP_CONCAT(photos.name) AS photo and you can get all the photos name by comma seperated list ,i have used ->group_by('vehicle.idvehicle'); so for one vehicle group all the photos will be merged by comma but as in your question you stated you need the one photo so i used the SUBSTRING_INDEX you can also get the latest photo by using the ORDER by in GROUP_CONCAT if photo id is auto incremented like SUBSTRING_INDEX(GROUP_CONCAT(photos.name ORDER BY photo.id DESC),',',1) AS photo

$this->db
        ->select("vehicle.idvehicle, vehicle.mark,
         vehicle.model, vehicle.type, vehicle.author_id, users.nick, 
         SUBSTRING_INDEX(GROUP_CONCAT(photos.name),',',1) AS photo,",FALSE)
        ->from('xxxxxsld_auto.vehicle')
        ->join('users', 'vehicle.author_id = users.userid')
        ->join('photos', 'vehicle.idvehicle = photos.vehicle_id')
        ->group_by('vehicle.idvehicle'); 
        ->get()
        ->result_array();

Or just use group by

$this->db
        ->select("vehicle.idvehicle, vehicle.mark,
         vehicle.model, vehicle.type, vehicle.author_id, users.nick, 
         photos.name,",FALSE)
        ->from('xxxxxsld_auto.vehicle')
        ->join('users', 'vehicle.author_id = users.userid')
        ->join('photos', 'vehicle.idvehicle = photos.vehicle_id')
        ->group_by('vehicle.idvehicle'); 
        ->get()
        ->result_array();

Edit From the comments you stated you need all photos so be aware of that fact the GROUP_CONCAT has a default limit of 1024 characters to concatenate but this can be increased by following the manual

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