在带有ORDER BY和LIMIT的代码点火器中使用UNION ALL会产生错误



我必须将包含两种类型post的两个不同表合并为一个包含所有post的表。我尝试过使用UNIONALL,在必须添加分页之前,我得到了很好的结果。

$this->db->select("id,article_type,title,main_img1,open_date");
$this->db->from('table1');
$query1 = $this->db->get_compiled_select();
$this->db->reset_query();

$this->db->select("id,article_type,title,main_img1,open_date");
$this->db->from('table2');
$query2 = $this->db->get_compiled_select();
$this->db->reset_query();

$articles = $this->db->query($query1 . ' UNION ALL ' . $query2);

$data['total_rows'] = $articles->num_rows();

/*pagination*/
$page = $this->input->get('page') ? $this->input->get('page') : 1;
$this->load->library("pagination");
$this->config->load('pagination', true);
$config = $this->config->item('pagination');
$config['reuse_query_string'] = TRUE;
$config['query_string_segment'] = 'page';
$config["base_url"] = site_url('example/index');
$config["total_rows"] = $data['total_rows'];
$config["per_page"] = 9;
$config["offset"] = ($page - 1) * $config["per_page"];
$this->pagination->initialize($config);
$data['column_pagination'] = $this->pagination->create_links();

/* get records */
$query = $this->db->query($articles . 'ORDER BY open_date DESC, id DESC LIMIT ' . $config["offset"] . ',' . $config["per_page"]);
$data['article_posts'] = $query->result_array();

我使用的是现有的代码,统一的表似乎不适合ORDERBY和LIMIT。有人有解决方案吗??

更新:我的原始代码有一个query2!很抱歉打字错误。

您使用了错误的变量,请更改

$query = $this->db->query($articles . 'ORDER BY open_date DESC, id DESC LIMIT ' . $config["offset"] . ',' . $config["per_page"]);

$query = $this->db->query($query1 . ' UNION ALL ' . $query2 . ' ORDER BY open_date DESC, id DESC LIMIT ' . $config["offset"] . ',' . $config["per_page"]);

因为Articles不是字符串,所以它是一个数据库对象。您还需要在ORDERBY之前有一个空格,因为原始查询不包含该空格。

如果你真的想成为动态

$query = $this->db->query($this->db->last_query() . ' ORDER BY open_date DESC, id DESC LIMIT ' . $config["offset"] . ',' . $config["per_page"]);

顺便问一句,你知道你没有$query2吗?

最新更新