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 に答える