在codeigniter中加入两个数据库的查询

Anu*_*Anu 6 php mysql join multiple-databases codeigniter-2

我需要编写来自两个数据库的两个表的连接查询并获取连接的数据.例如,考虑我有一个数据库db1,它有一些名为companies,plans,customers的表.假设我需要加入两个表公司并计划在另一个数据库db2上使用另一个表'cdr',通过使用类似的列对它们进行分组.

我现在正在运行的查询如下:

function get_per_company_total_use ($custid)
        {         
                 $this->DB1->select('ph_Companies.CompanyName');
                 $this->DB1->where('ph_Companies.Cust_ID', $custid);
                 $this->DB2->select_sum('cdr.call_length_billable')->from('cdr');
                 $this->DB2->group_by('cdr.CompanyName');
                 $this->db->join('Kalix2.ph_Companies', 'Kalix2.ph_Companies.CompanyName = Asterisk.cdr.CompanyName');
                 $query = $this->db->get();
                 if($query->result()){
                     foreach ($query->result() as $value) {
                         $companies[]= array($value->CompanyName,$value->call_length_billable);
                          }
                     return $companies;
                 }
                 else 
                     return FALSE;
        }
Run Code Online (Sandbox Code Playgroud)

但我的查询不是获取数据并抛出错误.同样的查询,我在一个数据库上运行并正在运行.但我需要帮助才能找到如何使用两个数据库完成此操作.

Anu*_*Anu 5

如果需要连接两个数据库表,可以给出以下内容:

function get_per_company_total_use ($custid)
        {         
                 $this->db->select('Kalix2.ph_Companies.CompanyName');
                 $this->db->where('Kalix2.ph_Companies.Cust_ID', $custid);
                 $this->db->select_sum('Asterisk.cdr.call_length_billable')->from('Asterisk.cdr');
                 $this->db->group_by('Asterisk.cdr.CompanyName');
                 $this->db->join('Kalix2.ph_Companies', 'Kalix2.ph_Companies.CompanyName = Asterisk.cdr.CompanyName');
                 $query = $this->db->get();
                 if($query->result()){
                     foreach ($query->result() as $value) {
                         $companies[]= array($value->CompanyName,$value->call_length_billable);
                          }
                     return $companies;
                 }
                 else 
                     return FALSE;
        }
Run Code Online (Sandbox Code Playgroud)

实际上你不需要给出连接变量DB1或DB2,只需给出$ this-> db.

  • 如果数据库在不同的计算机上运行怎么办? (2认同)