【问题标题】:getting three records in descending order of each category using codeigniter使用codeigniter按每个类别的降序获取三个记录
【发布时间】:2014-09-03 14:02:14
【问题描述】:

我有两个类别,稍后我想获取每个类别的三个记录我找到了这个链接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;
}

然后我像这样创建基于 codeigniter 函数的查询

$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();

创建这个

(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 也可以完成,但我想使用查询。提前致谢

【问题讨论】:

  • 实际上我正在使用 codeigniter 的内置函数,例如 $this->db->select('*');和其他功能,那么我该如何实现呢。
  • 有什么方法可以实现吗?
  • GolezTrol 先生现在在编辑后看到我的问题。
  • 我看到你努力改进它。我投票重新打开它,我删除了反对票和我现在已经过时的 cmets。虽然我对 Codeigniter 了解不多,目前也没有时间深入研究,所以希望其他人能为您解答。
  • 我发布了在 codeigniter 中创建的简单查询

标签: php mysql codeigniter query-builder


【解决方案1】:

我不知道代码点火器,但基本上你希望它先进行联合,然后将顺序应用于整个集合。这将需要一个子查询。它应该会产生以下 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

希望对你有所帮助。

【讨论】:

  • 它给了我错误Error Code: 1060 Duplicate column name 'id'
  • 将 2 select * 替换为 select [fieldnames you want]
  • Error Code: 1222 The used SELECT statements have a different number of columns 在此查询后SELECT * FROM ((SELECT * FROM kt_media m INNER JOIN kt_category c ON m.category_id = c.id ) UNION ALL (SELECT m.media_files FROM kt_media m INNER JOIN kt_category c ON m.category_id = c.id)) T ORDER BY m.media_files DESC LIMIT 3
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-08
  • 1970-01-01
相关资源
最近更新 更多