[英]Join query of two databases in codeigniter
I need to write a join query of two tables from two databases and fetch the joined data. 我需要编写来自两个数据库的两个表的连接查询并获取连接的数据。 For eg, consider I have a database db1 which has some tables named companies, plans, customers.
例如,考虑我有一个数据库db1,它有一些名为companies,plans,customers的表。 Suppose I need to join the two tables companies and plans with another table 'cdr' on another database db2 by grouping them using a similar column.
假设我需要加入两个表公司并计划在另一个数据库db2上使用另一个表'cdr',通过使用类似的列对它们进行分组。
The query which I'm running right now is given below: 我现在正在运行的查询如下:
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;
}
But my query is not fetching the data and throwing an error. 但我的查询不是获取数据并抛出错误。 This same query, I have run on a single database and is working.
同样的查询,我在一个数据库上运行并正在运行。 But I need help to find how this can be done with two databases.
但我需要帮助才能找到如何使用两个数据库完成此操作。
You can just give the following if you need to join two database tables: 如果需要连接两个数据库表,可以给出以下内容:
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;
}
Here actually you need not give the connection variable DB1 or DB2, just give $this->db. 实际上你不需要给出连接变量DB1或DB2,只需给出$ this-> db。
I'm having table x in DB1 which contain id, name and y_id. 我在DB1中有表x,其中包含id,name和y_id。 In DB2 there is ay table with id and name
在DB2中有一个带有id和name的表
so if you need to get name of x and y in a same query the here is your answer: 所以,如果您需要在同一个查询中获取x和y的名称,这是您的答案:
$db = $this->load->database("DB2", TRUE);
$DB = $this->load->database("DB1", TRUE);
$DB->select('x.name as name1, y.name as name2');
$DB->from('x');
$DB->join($db->database.'.y','x.y_id = y.id');
$res = $DB->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.