【发布时间】: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