【问题标题】:Codeigniter ->from(multiple tables)Codeigniter -> from(多个表)
【发布时间】:2013-07-31 06:46:42
【问题描述】:

大家好 stackoverflow :) 我想从两个表中获取数据。我不想要任何特定的 'where' 选项,所以这是我的模型代码:

$this->db->from('table1, table2');      
$this->db->order_by('table1.date, table2.date', "desc");
$query = $this->db->get('', $num, $offset);

return $query->result_array();

这样我只能从“table2”中获取信息,它只包含 1 篇文章,并且这篇文章在页面上重复了几次。这两个表具有相同的结构,我希望以这种方式编写“order_by”会有所帮助,但没有。如果我进行任何其他操作,我只能从一张表中获取信息。按日期排序很重要。 希望任何人都会发现这个问题很有趣并且也会有所帮助。提前致谢!

编辑部分: 功能:

$this->db->get("table1");

$comm_numbers = $this->db->count_all_results("table1");

$config['base_url'] = base_url();
$config['total_rows'] = $comm_numbers;
$config['per_page'] = '5';
$config['uri_segment'] = 1;
$this->pagination->initialize($config);

$this->load->model("model_get_all");
$data["results"] = $this->model_get_all->getData1($config['per_page'], $this->uri->segment(1));
$this->load->helper('url');

【问题讨论】:

  • 告诉我们Table1和Table2的列
  • 如果两个表的表结构相同,我认为你会想使用UNION 而不是连接
  • id、标题、文本、视图、日期、图像。我已经使用过这些表,如果我分别使用每个表,我会从它们中检索信息。

标签: php codeigniter


【解决方案1】:

试试这个:

$this->db->query('SELECT id, title, text, views, date, image FROM table1 UNION SELECT id, title, text, views, date, image FROM tablee2');

更新: 使用 CodeIgniter 分页查询:

$this->db->query("SELECT id, title, text, views, date, image FROM table1 UNION SELECT id, title, text, views, date, image FROM tablee2 LIMIT $offset, $num");

更新 2: 好的,我只更改 $offset 变为 null 时的位置。

$this->db->get("table1");

$comm_numbers = $this->db->count_all_results("table1");

$config['base_url'] = base_url();
$config['total_rows'] = $comm_numbers;
$config['per_page'] = '5';
$config['uri_segment'] = 1;
$this->pagination->initialize($config);

$page = ($this->uri->segment(1)) ? $this->uri->segment(1) : 0;

$this->load->model("model_get_all");
$data["results"] = $this->model_get_all->getData1($config['per_page'], $page);
$this->load->helper('url');

【讨论】:

  • 是的,终于成功了!感谢 Erman,也感谢 Koala_Dev。很好的方法。
  • 但是我们有什么办法可以保存 $num 和 $offset 用于分页?
  • 是的。我现在将更新答案,我将添加$num$offset
  • 感谢如此快速的更新,但我得到了错误号:1327 未声明的变量:$offset。我正在使用默认的 CI 分页方法
  • 尝试使用 " " (double ') @AlexanderYakovluk
猜你喜欢
  • 2012-10-05
  • 1970-01-01
  • 1970-01-01
  • 2019-07-31
  • 1970-01-01
  • 2015-11-22
  • 2013-08-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多