0

我正在使用 MYSQL/Codeigniter。如果传递的值为空,MySQL 查询如何忽略条件,例如以下示例:

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();
  }
4

2 回答 2

2

尝试这个:

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
于 2013-02-06T13:51:07.873 回答
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();
于 2013-02-07T06:04:45.660 回答