2017-02-11 76 views
1

我是從2頁不同的表運行查詢選擇數據:笨不返回相同的結果,查詢

$this->db->select('a.any_id, a.name'); 
$this->db->from('table1 a, table2 b'); 
$this->db->where('a.any_id = b.any_id'); 
$this->db->where('b.other_id = "$myId"'); 

如果運行此查詢在phpMyAdmin它返回了一定的效果,但是當我運行笨驗證碼它返回一個空數組。

任何提示?這真讓我抓狂。

+0

'''$這個 - > DB->選擇( 'a.any_id,a.name'); $ this-> db-> from('table1 a,table2 b'); $ this-> db-> where('a.any_id = b.any_id',NULL); ('b.other_id =「$ myId」',NULL); $ query = $ this-> db-> get(); return $ query-> result();''' – Mohammad

+0

不,它沒有工作。相同的0結果與之前的 –

+0

和此'''$ this-> db-> select('a.any_id,a.name'); $ this-> db-> from('table1 a,table2 b'); $ this-> db-> where('a.any_id','b.any_id'); $ this-> db-> where('b.other_id',$ myId); $ query = $ this-> db-> get(); return $ query-> result();''' – Mohammad

回答

0

我想是因爲你試圖連接兩個表並在userguide你不使用CodeIgniter的$this->db->join()向下滾動到你看不出接縫()https://www.codeigniter.com/user_guide/database/query_builder.html

public function example($myID) { 
    $this->db->select('a.any_id, a.name'); 
    $this->db->from('table1 a', 'LEFT'); 
    // $this->db->from('table1 a'); 
    $this->db->join('table2 b', 'b.any_id = a.any_id', 'LEFT'); 
    $this->db->where('a.any_id', 'b.any_id'); 
    $this->db->where('b.other_id', $myId); 
    $query = $this->db->get(); 

    return $query->result(); 
} 

然後vardump它。

+0

將多個表在FROM是好的,它叫做CROSS JOIN,那麼如果你向WHERE子句添加約束條件'tablea = tableb',它會將它有效地轉換爲INNER JOIN。 –

0

大家好,謝謝你的回覆。

它與使用連接子句無關。

我只是改變

$this->db->where('b.other_id = "$myId"'); 

$this->db->where('b.other_id', $myId); 

和完美。還不確定爲什麼,因爲第一行適用於簡單的查詢。

+0

第一個只是使用第一行作爲完整的地方,第二個分裂它說'這個專欄'=這個約束。兩個都是有效的,儘管第一個應該寫成:'$ this-> db-> where('b.other_id ='。$ myId);' –

0

試試這個

 $this->db->select('a.any_id.*,table2.name'); 
     $this->db->from('table1 a'); 
     $this->db->join('tabl2 b', 'a.id=b.id', 'left'); 
     $this->db->where('a.id',$id);  
     $query = $this->db->get(); 
     return $query->result(); 
相關問題