mysql - 如果字段值为 0 或 1,如何选择 sum?

标签 mysql codeigniter web

当我的列 is_active0 时,我想对字段求和,并且我想将其显示到我的仪表板页面。如果 is_active1 它应该跳过而不是求和。

如何做到这一点?有什么查询?我在 CodeIgniter 中构建了示例查询:

$this->db->select_sum('is_active');
    $query = $this->db->get('postfes');
    if ($query->num_rows() = 0) {
        return $query->num_rows()->is_active;
    } else {
        return 0;
    }

最佳答案

您需要使用where条件

$this->db->select_sum('is_active'); // the field you want to sum
$this->db->where('is_active', 0)
$data = $this->db->get('postfes')->row();
if ($data) {
    return $data->is_active;
} else {
    return 0;
}

如果您想计算 is_active = 0 的位置,则使用

$this->db->select('count(*) as total'); // the field you want to sum
    $this->db->where('is_active', 0)
    $data = $this->db->get('postfes')->row();
    if ($data) {
        return $data->total;
    } else {
        return 0;
    }

关于mysql - 如果字段值为 0 或 1,如何选择 sum?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59433489/

相关文章:

jquery 和 codeigniter

php - 使用 Ion Auth 在 Codeigniter 中创建用户角色和配置文件

javascript - jQuery 将 css 链接附加到 iframe head

php - Laravel 未安装依赖项 php 版本不正确

mysql - 在 SQL 中检查每个月每天有多少次

mysql - 有任何理由使用 TINYTEXT 吗?

c# - LINQ to SQL (NHibernate) : OrderBy vs OrderByDescending abstraction

python - 运行 "blog"的tornado Demos的问题

php - 从多维关联后数组创建关联数组 - Codeigniter

javascript - 直接从 Javascript 代码访问 SVG 文件