我正在使用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
关于mysql - 如果值为空,则忽略条件MYSQL/Codeigniter,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14730627/