我正在使用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();
}
答案 0 :(得分: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
答案 1 :(得分: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();