2014-09-03 55 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