You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用UNION ALL合并两张表获取最新10条文章报错求助

问题与解决:合并两张表获取最新公开文章(CodeIgniter)

错误原因

你遇到的Object of class CI_DB_mysqli_result could not be converted to string错误,核心问题是错误地将数据库查询结果对象当作字符串拼接SQL:

  • 执行$articles = $this->db->query($query1 . ' UNION ALL ' . $query2);后,$articles是查询结果集对象,而非SQL字符串
  • 后续试图将该对象与ORDER BY语句拼接,触发类型转换错误

修正后的代码

正确思路是先拼接包含UNION ALL、排序和限制的完整SQL字符串,再一次性执行查询:

// 编译column表的查询SQL
$this->db->select("id,article_type,title,main_img1,open_date");
$this->db->from('column');
$this->db->where('open_flg', 1);
$this->db->where('open_date <= NOW()');
$this->db->where('(close_date >= NOW() OR close_date = \'0000-00-00 00:00:00\')');
$query1 = $this->db->get_compiled_select();
$this->db->reset_query();

// 编译cases表的查询SQL
$this->db->select("id,article_type,title,main_img1,open_date");
$this->db->from('cases');
$this->db->where('open_flg', 1);
$this->db->where('open_date <= NOW()');
$this->db->where('(close_date >= NOW() OR close_date = \'0000-00-00 00:00:00\')');
$query2 = $this->db->get_compiled_select();
$this->db->reset_query();

// 拼接完整UNION ALL查询语句,包含排序和条数限制
$full_sql = "(SELECT * FROM ($query1) AS t1) UNION ALL (SELECT * FROM ($query2) AS t2) ORDER BY open_date DESC LIMIT 10";

// 执行查询并获取结果
$query = $this->db->query($full_sql);
$data['article_posts'] = $query->result_array();

关键说明

  • get_compiled_select()返回未执行的SQL字符串,可直接拼接
  • 给子查询加别名(如t1、t2)是为了兼容MySQL对UNION子查询的语法要求
  • 排序和LIMIT必须放在整个UNION语句末尾,才能对合并后的结果集生效

内容的提问来源于stack exchange,提问作者Toru Kawahata

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 02:25:29