2014-09-03 53 views
2

我有兩大類,我想取三個記錄每個類別的下降每個類別的順序後,我發現在這之後這個鏈接UNION query with codeigniter's active record pattern我改變我的DB_Active_rec文件,並添加以下代碼也獲得三個記錄使用笨

var $unions = array(); 

public function union_push($table = '') { 
    if ($table != '') { 
     $this->_track_aliases($table); 
     $this->from($table); 
    } 

    $sql = $this->_compile_select(); 

    array_push($this->unions, $sql); 
    $this->_reset_select(); 
} 

public function union_flush() { 
    $this->unions = array(); 
} 

public function union() { 
    $sql = '(' . implode(') union (', $this->unions) . ')'; 
    $result = $this->query($sql); 
    $this->union_flush(); 
    return $result; 
} 

public function union_all() { 
    $sql = '(' . implode(') union all (', $this->unions) . ')'; 
    $result = $this->query($sql); 
    $this->union_flush(); 
    return $result; 
} 

,然後我創建這樣

$this->db->select("*"); 
$this->db->from("media m"); 
$this->db->join("category c", "m.category_id=c.id", "INNER"); 
$this->db->order_by("m.media_files", "DESC"); 
$this->db->limit(3); 
$this->db->union_push(); 
$this->db->select("*"); 
$this->db->from("media m"); 
$this->db->join("category c", "m.category_id=c.id", "INNER"); 
$this->db->order_by("m.media_files", "DESC"); 
$this->db->limit(3); 
$this->db->union_push(); 
$getMedia = $this->db->union_all(); 

CodeIgniter的基於函數查詢創建此

(SELECT * FROM media m INNER JOIN category c ON 
m.category_id = c.id ORDER BY m.media_files DESC LIMIT 3) 
UNION ALL 
(SELECT * FROM media m INNER JOIN category c ON 
m.category_id = c.id ORDER BY m.media_files DESC LIMIT 3) 

現在它是提取記錄,但不正確我想只使用查詢,它顯示六個記錄第一個查詢獲取3個記錄和第二個查詢獲取三個記錄現在記錄是重複的我檢查記錄的id是6,5,4並再次6,5,4。它也可以通過PHP完成,但我想使用查詢。在此先感謝

+0

其實我使用codeigniter的內置函數,如$ this-> db-> select('*');和其他功能,所以我如何實現它。 – user3833682 2014-09-03 14:23:28

+0

有什麼辦法可以實現它嗎? – user3833682 2014-09-04 10:12:09

+0

先生'GolezTrol'現在在編輯後看到我的問題。 – user3833682 2014-09-04 11:27:19

回答

0

我不知道代碼點火器,但基本上你希望它先做聯合,然後在整個集合上應用順序。這將需要一個子查詢。它應該導致下面的SQL查詢:

select * from 
    ((SELECT * FROM media m INNER JOIN category c ON m.category_id = c.id) 
    UNION ALL 
    (SELECT * FROM media m INNER JOIN category c ON m.category_id = c.id)) T 
ORDER BY m.media_files DESC LIMIT 3 

希望它可以幫助你一些。

+0

它給我錯誤'錯誤代碼:1060 重複列名'id'' – user3833682 2014-09-04 14:34:51

+0

查詢並沒有解決我的問題,所以我必須做什麼? – user3833682 2014-09-08 05:06:06

+0

用'select [fieldnames you want]替換2'select *'' – Alfons 2014-09-08 07:43:47