使用 ActiveRecord 统计 id 匹配且另一列匹配两个值之一的行

Use ActiveRecord to count rows where id is matched and another column matches one of two values

我需要在 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 的 Active Record 查询构建方法来做到这一点?

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() accepts an optional third parameter. If you set it to FALSE, CodeIgniter will not try to protect your field or table names with backticks.

参考: https://www.codeigniter.com/userguide3/database/query_builder.html#looking-for-specific-data

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');
}

将组与查询生成器结合使用

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) = 'submitted' OR lower(ResponseStatus) = 'inqueue' ) AND SMSUsageID = '1'

与其尝试将 OR 硬塞进您的查询中,不如使用 IN().

代码:

public function submittedSMSCount(int $smsUsageID): int
{
    return $this->db->where_in('LOWER(ResponseStatus)', ['submitted', 'inqueue'])
                    ->where('SMSUsageID', $smsUsageID)
                    ->count_all_results('smslog_tbl');
}

这将导致 LOWER(ResponseStatus) 匹配两个白名单值之一并且 SMSUsageID 将等于 $smsUsageID