2010-06-04 48 views
19

我使用下面的代碼從一個MySQL數據庫與代碼點火器Web應用程序中進行選擇:笨:如何使用WHERE子句和OR子句

$query = $this->db->get_where('mytable',array('id'=>10)); 

這個偉大的工程!但是我想用CI庫編寫下面的MySQL語句?

SELECT * FROM `mytable` WHERE `id`='10' OR `field`='value' 

任何想法? 謝謝!

回答

32
$where = "name='Joe' AND status='boss' OR status='active'"; 

$this->db->where($where); 
+0

雖然我只有3年晚了,但從哪個表中它會得到它?如何指定表格 – 2014-01-11 21:34:05

+2

雖然我是一個月後的3/4,但在您定義where子句後仍然執行以下操作: $ this-> db-> get(「tbl_name」); – James 2014-02-03 07:20:03

+0

'$ where ='(name =「Joe」AND status =「boss」OR status =「active」)';'參見:http://stackoverflow.com/a/9941814/594235 – Sparky 2014-10-12 18:38:27

28

您可以使用該or_where() - 例如,從CI文檔:

$this->db->where('name !=', $name); 

$this->db->or_where('id >', $id); 

// Produces: WHERE name != 'Joe' OR id > 50 
+0

根據文檔or_where是棄用。 http://codeigniter.com/user_guide/database/active_record.html – 2010-06-04 16:38:10

+6

我相信你可能誤解了這一點。在我看來,舊方法或where()已被棄用,以支持新方法or_where()。 – Rookwood 2010-06-04 16:42:43

+0

感謝您澄清這一點!甚至4年後的大幫助! – Awilson089 2014-04-21 19:29:11

11

您可以使用此:

$this->db->select('*'); 
$this->db->from('mytable'); 
$this->db->where(name,'Joe'); 
$bind = array('boss', 'active'); 
$this->db->where_in('status', $bind); 
+0

我如何得到結果? – Sahan 2015-06-03 22:38:05

+0

結果存儲在哪裏? – Sahan 2015-06-03 22:38:14

6

活動記錄方法or_where將用於:

$this->db->select("*") 
->from("table_name") 
->where("first", $first) 
->or_where("second", $second); 
0
$where = "name='Joe' AND status='boss' OR status='active'"; 

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

雖然我一個月的3/4晚了,你還在執行以下命令,其中被定義後您的條款... $this->db->get("tbl_name");

0

什麼工作對我來說:

$where = ''; 
    /* $this->db->like('ust.title',$query_data['search']) 
     ->or_like('usr.f_name',$query_data['search']) 
     ->or_like('usr.l_name',$query_data['search']);*/ 
     $where .= "(ust.title like '%".$query_data['search']."%'"; 
     $where .= " or usr.f_name like '%".$query_data['search']."%'"; 
     $where .= "or usr.l_name like '%".$query_data['search']."%')"; 
     $this->db->where($where); 



$datas = $this->db->join(TBL_USERS.' AS usr','ust.user_id=usr.id') 
      ->where_in('ust.id', $blog_list) 
      ->select('ust.*,usr.f_name as f_name,usr.email as email,usr.avatar as avatar, usr.sex as sex') 
      ->get_where(TBL_GURU_BLOG.' AS ust',[ 
       'ust.deleted_at'  => NULL, 
       'ust.status'  => 1, 
      ]); 

我必須做的這創建一個這樣的查詢:

SELECT `ust`.*, `usr`.`f_name` as `f_name`, `usr`.`email` as `email`, `usr`.`avatar` as `avatar`, `usr`.`sex` as `sex` FROM `blog` AS `ust` JOIN `users` AS `usr` ON `ust`.`user_id`=`usr`.`id` WHERE (`ust`.`title` LIKE '%mer%' ESCAPE '!' OR `usr`.`f_name` LIKE '%lok%' ESCAPE '!' OR `usr`.`l_name` LIKE '%mer%' ESCAPE '!') AND `ust`.`id` IN('36', '37', '38') AND `ust`.`deleted_at` IS NULL AND `ust`.`status` = 1 ;