2017-06-21 124 views
0

我正在使用Codeigniter,我想要做的是返回連接表(item_gallery)gallery_id是最低值的查詢。而主要查詢按項目desc排序post_datecodeigniter活動記錄group_by返回加入表記錄的隨機排序編號

以下代碼group_by選擇item_gallery gallery_id的隨機值。但我想要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(); 
} 

數據庫結構

項目表

| id | slug | user_id | post_date | 

| 12 | test | 111 | 12/5/2017 | 

項目庫

| gallery_id | item_id |  image  | 

|  121 | 12  | profile.png | -- i want this record selected 
|  122 | 12  | gallery.png | 

回答

0
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(); 
} 
0

更換

$this->db->order_by('items.post_date', 'Desc'); 

隨着

$this->db->order_by('items.id', 'Desc'); 
+0

我想 「item_gallery.id」 最低值,而items.post_date DESC –

+0

然後用'item_gallery.id'取代'items.post_date' –

+0

$這個 - > DB-> GROUP_BY( 「item_gallery.item_id」);應該選擇聯接表item_gallery.id的較低值。 while $ this-> db-> order_by('items.post_date','Desc'); –