我需要在codeigniter中创建一个查询,如下所示:
SELECT COUNT(*) AS `numrows` FROM `smslog_tbl` WHERE (lower(ResponseStatus) = 'submitted' OR lower(ResponseStatus) = 'inqueue') AND `SMSUsageID` = '1'
所以我在模型中创建了一个函数:
function submittedSMSCount($smsUsageID) {
$this->db->where('lower(ResponseStatus)', 'submitted');
$this->db->or_where('lower(ResponseStatus)', 'inqueue');
$this->db->where('SMSUsageID', $smsUsageID);
return $this->db->count_all_results('smslog_tbl');
}
但此函数会生成如下查询:
SELECT COUNT(*) AS `numrows` FROM `smslog_tbl` WHERE lower(ResponseStatus) = 'submitted'OR lower(ResponseStatus) = 'inqueue' AND `SMSUsageID` = '1'
由于条件的原因,这两个查询会产生不同的结果。我需要将 OR 条件分组以获得正确的结果。如何使用codeigniter
执行此操作答案 0 :(得分:2)
function submittedSMSCount($smsUsageID) {
$this->db->where(
"(lower(ResponseStatus) = 'submitted' OR lower(ResponseStatus) = 'inqueue')",
NULL,
FALSE
);
$this->db->where('SMSUsageID', $smsUsageID);
return $this->db->count_all_results('smslog_tbl');
}
$this->db->where()
接受可选的第三个参数。如果你设置 它为FALSE,CodeIgniter不会试图保护你的领域或表 带反叛的名字。
参考: https://www.codeigniter.com/userguide3/database/query_builder.html#looking-for-specific-data
答案 1 :(得分:1)
function submittedSMSCount($smsUsageID) {
$where = "(lower(ResponseStatus) = 'submitted' OR lower(ResponseStatus) = 'inqueue')";
$this->db->where($where);
$this->db->where('SMSUsageID', $smsUsageID);
return $this->db->count_all_results('smslog_tbl');
}
答案 2 :(得分:0)
将组与查询构建器一起使用
function submittedSMSCount($smsUsageID) {
$this->db->select('COUNT(*) AS numrows')
->group_start()
->where('lower(ResponseStatus)', 'submitted')
->or_where('lower(ResponseStatus)','inqueue')
->group_end()
->where('SMSUsageID', $smsUsageID);
return $this->db->get('smslog_tbl');
}
输出
SELECT COUNT(*)AS numrows FROM smslog_tbl
WHERE(lower(ResponseStatus)='提交'或更低(ResponseStatus)=' inqueue')AND {{1 }} =' 1'