我有两个类别,我想获取每个类别的三个记录,稍后我找到了这个链接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完成,但我想使用查询。提前感谢
发布于 2014-09-04 22:28:30
我不知道代码触发器,但基本上你想让它先做并集,然后在整个集合上应用order by。这将需要一个子查询。它应该产生以下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希望能对你有所帮助。
https://stackoverflow.com/questions/25646387
复制相似问题