首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用codeigniter按每个类别的降序获取三条记录

使用codeigniter按每个类别的降序获取三条记录
EN

Stack Overflow用户
提问于 2014-09-03 22:02:14
回答 1查看 1.8K关注 0票数 2

我有两个类别,我想获取每个类别的三个记录,稍后我找到了这个链接UNION query with codeigniter's active record pattern,之后我更改了我的DB_Active_rec文件,并添加了以下代码

代码语言:javascript
复制
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;
}

然后创建基于codeigniter函数的查询,如下所示

代码语言:javascript
复制
$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();

创建此

代码语言:javascript
复制
(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完成,但我想使用查询。提前感谢

EN

回答 1

Stack Overflow用户

发布于 2014-09-04 22:28:30

我不知道代码触发器,但基本上你想让它先做并集,然后在整个集合上应用order by。这将需要一个子查询。它应该产生以下SQL查询:

代码语言:javascript
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25646387

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档