【问题标题】:How to select sum if the field has a value of either 0 or 1?如果字段的值为 0 或 1,如何选择 sum?
【发布时间】:2020-04-13 10:53:22
【问题描述】:

当我的列 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;
    }

【问题讨论】:

  • sum 需要使用哪一列?

标签: mysql codeigniter web


【解决方案1】:

你需要使用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;
    }

【讨论】:

  • 我忘了如何使用 'where' 条件大声笑,它显示但为什么只有一个?,在我的文件中我有 3 is_active = 0
  • 你的意思是你需要计算is_active为0的总数?
猜你喜欢
  • 2012-02-11
  • 2019-08-14
  • 2014-06-01
  • 1970-01-01
  • 2022-08-09
  • 1970-01-01
  • 2012-01-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多