2016-08-25 56 views
1

我已經檢查對此其他問題與SQL語句或條款,但未能解決問題如何改寫笨

$this->db->where(array('sender_deletedS' => 1, 'receiver_deleted' => 0)); 
      $this->db->or_where(array('sender_deletedS' => 0, 'receiver_deleted' => 1)); 
      $this->db->or_where(array('sender_deletedS' => 0, 'receiver_deleted' => 0)); 
      $query2 = $this->db->get('message'); 

它產生

SELECT * FROM `message` WHERE `sender_deletedS` = 1 AND `receiver_deleted` =0 OR `sender_deletedS` =0 OR `receiver_deleted` = 1 OR `sender_deletedS` =0 OR `receiver_deleted` =0 

,但我想這

SELECT * FROM `message` WHERE `sender_deletedS` = 1 AND `receiver_deleted` =0 OR `sender_deletedS` =0 AND `receiver_deleted` = 1 OR `sender_deletedS` =0 AND `receiver_deleted` =0 

回答

1
$sql = "sender_deleted = 1 AND receiver_deleted = 0 OR sender_deleted = 0 AND receiver_deleted = 1 OR 
sender_deleted = 0 AND receiver_deleted = 0 
"; 

$this->db->where($sql); 

$this->db->get('message') ; 

該聲明可以被存儲並且使用如上例所示的變量執行

1

如果您使用Query Builder或Active Record非常混亂,請嘗試傳統的SQL方法。這也容易理解

$this->db->query("SELECT * FROM `message` WHERE `sender_deletedS` = 1 AND `receiver_deleted` =0 OR `sender_deletedS` =0 AND `receiver_deleted` = 1 OR `sender_deletedS` =0 AND `receiver_deleted` =0"); 

or_where會產生一個OR加入語句。如果其合併其行爲爲AND

實施例01

$this->db->or_where('user_id =', 0); 
$this->db->or_where('member_id =', 1); 

輸出將是

WHERE user_id = 0 OR member_id = 1 

實施例02

$this->db->or_where(array('user_id' => 0, 'member_id' => 1)); 

輸出將是

WHERE user_id = 0 AND member_id = 1 

實施例03

$this->db->or_where(array('user_id' => 0, 'member_id' => 1)); 
$this->db->or_where('library_id =', 0); 

輸出將是

WHERE user_id = 0 AND member_id = 1 OR library_id = 0 

$this->db->or_where() in codeigniter.com