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

0s0u357o  于 2022-12-07  发布在  其他
关注(0)|答案(1)|浏览(120)

我必须将两个包含两种类型帖子的不同表合并到一个包含所有帖子的表中。我已经尝试使用UNION ALL,直到我必须添加分页为止,我都得到了很好的结果。

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

我使用的是现有的代码,似乎一个统一的表不适合ORDER BY和LIMIT。有人有解决方案吗?
更新:我有一个查询2对我的原始代码!对不起的错字。

vom3gejh

vom3gejh1#

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

$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不是一个String,它是一个数据库对象。您还需要在ORDER BY之前添加一个空格,因为原始查询不包含空格。
如果你真的想充满活力

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

顺便说一句,你知道你没有一个$query2?

相关问题