2013-02-06 59 views
0

我正在使用MYSQL/Codeigniter。 MySQL查詢如何可以忽略的條件,如果傳遞的值是空的,這樣的例子:如果值爲空,則忽略條件MYSQL/Codeigniter

function get_category($category_id = 0){ 

return $this->db->query("SELECT * FROM {$this->table} c 
        INNER JOIN db_category_event ce 
        ON ce.category_id = c.category_id 
        INNER JOIN db_event_type e 
        ON e.event_id = ce.event_id 
        WHERE c.category_id = {$category_id} 
        WHERE c.visible = 1 AND e.visible = 1") 
      ->result(); 
    } 

回答

1

試試這個:

SELECT * 

FROM {$this->table} c 

     INNER JOIN db_category_event ce 
     ON ce.category_id = c.category_id 

     INNER JOIN db_event_type e 
     ON e.event_id = ce.event_id 

WHERE ({$category_id} IS NULL OR c.category_id = {$category_id}) 
     AND c.visible = 1 AND e.visible = 1 

或者,如果該參數被作爲零來對待,這應該工作:

SELECT * 

FROM {$this->table} c 

     INNER JOIN db_category_event ce 
     ON ce.category_id = c.category_id 

     INNER JOIN db_event_type e 
     ON e.event_id = ce.event_id 

WHERE ({$category_id} = 0 OR c.category_id = {$category_id}) 
     AND c.visible = 1 AND e.visible = 1 
+0

謝謝,它的工作正常:) –

0

嘗試這個

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

$this->db->from($this->table c); 

$this->db->join('db_category_event ce', 'ce.category_id = c.category_id', 'inner'); 

$this->db->join('db_event_type e', 'e.event_id = ce.event_id', 'inner'); 

    if($category_id >0) 
    { 
    $this->db->where(c.category_id=$category_id); 
    } 

    $this->db->where(c.visible = 1); 

    $this->db->where(e.visible = 1); 

    $query = $this->db->get();