简体   繁体   中英

Sql table join with no direct relation [ codeigniter ]

I want to join tables where as table1 and table2 are common fields and table2 contain field record_id whos description is in table3 field record_desc what would be query?

There is no direct relation between table1 and table3

I tried like this but won't work.

$this->db->select('*');    
$this->db->from('table1');
$this->db->join('table2', 'table1.id = table2.id');
$this->db->join('table3', 'table2.record_id= table3.record_desc');
$query = $this->db->get();

I think this line is incorrect

$this->db->join('table3', 'table2.record_id= table3.record_desc');

because table3.record_desc is not the foreign key from table 2 to table 3 right ?

The query may be like this

$this->db->join('table3', 'table2.record_id= table3.record_id');

because you have to have a foreign key to match records in table 2 and table 3 .

and when you are selecting the result if you are doing like

$this->db->select('*'); 

If you have same column name in each table , only one column will appear in the result .

so try to get only columns you want like this

$this->db->select('table1.id,table2.record_id,table3.record_desc'); 

Hope this helps .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM