2017-09-22 76 views
0

我有2個表從表1中的值在表中定義的列的值2

表1包含

id    site 
    1    A1 
    2    A2 
    3    B1 
    4    B2 

表2包含

nesite   fesite  
    A1    A2 
    B1    A1 
    A2    B2 

我可以呼應表2作爲來自表1的id?like,

nesite   fesite  
    1    2 
    3    1 
    2    4 

到目前爲止,我已經嘗試了一些查詢,沒有任何工作。這是我模型的最後一個形狀。

function site(){ 
    $this->db->select('*'); 
    $this->db->from('table2'); 
    $this->db->join('table1','table1.site = table2.nesite OR table1.site = table2.fesite'); 
    $query = $this->db->get(); 
    return $query->result(); 
} 

回答

2

您可以加入與表table1兩倍b。使用不同的列像

select a1.id as nesite, 
a2.id as fesite 
from table2 b 
join table1 a1 on (b.nesite = a1.site) 
join table1 a2 on (b.fesite = a2.site) 

DEMO

活動記錄查詢將會像

$this->db->select('a1.id as nesite,a2.id as fesite',FALSE); 
$this->db->from('table2 b'); 
$this->db->join('table1 a1','b.nesite = a1.site'); 
$this->db->join('table1 a2','b.fesite = a2.site'); 
$query = $this->db->get(); 
$query->result(); 
+1

謝謝你,我有之前嘗試過,但沒有顯示任何東西,我想我錯過了「ON」中的一些東西,:D – andrianrion

相關問題