Joining tables from two databases using codeignite

2019-09-10 02:28发布

问题:

In order to write query in codeigniter you need to write something like $this->db->query or $someDB->query. But what if I want to join tables from two different databases?

I know that I can do it through pure php, using mysqli_connect and writing something like:

SELECT * FROM db1.table1 JOIN db2.table2

But is there a way to do it using codeigniter?

回答1:

You can try to use the function I am using in a project I am working on right now... Please see the code below...

function join_table()
{
    $this->db->select(//column name, //column name, //column name);
    $this->db->from(//table1 name);
    $this->db->join(//table2 name, //table1 name.//column name = //table2 name.//column name');
    $this->db->where(//condition);
    return $this->db->get()->result();
}


回答2:

Use query method from CodeIgniter and pass any complex sql query trough:

$query = $this->db->query("SELECT * FROM dbname1.table t1 JOIN db2.table t2 ON t2.column = t1.column");

foreach ($query->result() as $row)
{
    print_r($row);
}


回答3:

This simple join of student and teacher table with same column name , Hope you will get it .

$this->db->select("s.*,t.*");
$this->db->from("student as s");
$this->db->join("teacher as t","s.student_id = t.student_id","both");
$result = $this->db->get()->result_array();
return $result;

also you want single row try row_array(); instead of result_array();