[英]Ignore a condition if value is null MYSQL/Codeigniter
我正在使用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();
}
尝试这个:
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
尝试这个
$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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.