问题
I'm using Codeigniter, what I want to do is a query that returns joined table (item_gallery) gallery_id is lowest value. while main query ordered by desc of items post_date
the below code group_by select random value of item_gallery gallery_id. but i want the lowest value of item_gallery gallery_id.
public function shopItems($id) {
$this->db->select("*");
$this->db->from('items');
$this->db->join('item_gallery', 'items.id = item_gallery.item_id', 'left');
$this->db->where('items.user_id', $id);
$this->db->order_by('items.post_date', 'Desc');
$this->db->group_by("item_gallery.item_id");
$query = $this->db->get();
return $query->result();
}
database Structure
items table
| id | slug | user_id | post_date |
| 12 | test | 111 | 12/5/2017 |
items Gallery
| gallery_id | item_id | image |
| 121 | 12 | profile.png | -- i want this record selected
| 122 | 12 | gallery.png |
回答1:
Replace
$this->db->order_by('items.post_date', 'Desc');
With
$this->db->order_by('items.id', 'Desc');
回答2:
public function shopItems($id, $limit, $start) {
date_default_timezone_set('Asia/Colombo');
$expire = date('Y-m-d');
$this->db->select("*,(SELECT image FROM item_gallery WHERE item_id =
items.id ORDER BY gallery_id ASC LIMIT 1) AS profile_img");
$this->db->from('items');
$this->db->join('item_gallery', 'items.id = item_gallery.item_id', 'left');
$this->db->where('items.exp_date >', $expire);
$this->db->group_start();
$this->db->where("items.status = 'yes'");
$this->db->or_where("items.status = 'edit'");
$this->db->group_end();
$this->db->where('items.user_id', $id);
$this->db->limit($limit, $start);
$this->db->order_by('items.post_date', 'Desc');
$this->db->group_by("item_gallery.item_id");
$query = $this->db->get();
return $query->result();
}
来源:https://stackoverflow.com/questions/44668853/codeigniter-active-records-group-by-returns-random-ordering-of-joined-table-reco