【问题标题】:How to count total no of records based on value using codiegniter如何使用codeigniter根据值计算记录总数
【发布时间】:2017-11-03 09:42:03
【问题描述】:
  id | name | status

   1 |  name | yes

   2 |  name | no 

   3 |  name | yes

如何使用活动记录计算值为 yes 和值为 no 的总状态?喜欢的计数是:yes = 2no = 1

这是我迄今为止尝试过的

$this->db->select('count(status));
//$this->db->select('count(where status == 'yes')); // not working
$query = $this->db->get();

【问题讨论】:

    标签: php mysql codeigniter activerecord


    【解决方案1】:

    使用 CI 的 where 方法添加 where 条件。如下所示更改您的查询:

    $this->db->select('count(status)');
    $this->db->where('status','yes'); // apply where
    $query = $this->db->get();
    

    要获取所有状态计数,请使用 group by 子句

    $this->db->select('status,count(status)');
    $this->db->group_by('status'); // apply group by
    $query = $this->db->get();
    

    【讨论】:

    • 感谢您的回答,但为此我需要两个查询,一个用于状态是,一个用于状态否。我们可以使用单个查询吗? @B.Desai
    • 使用 group by
    【解决方案2】:

    试试这个

    $this->db->select('*');
            $this->db->from('yourtablename');
            $this->db->where("(status = 'yes' AND id = '2' )", NULL, FALSE);
            $query = $this->db->get();
    
            return $query->num_rows();
    

    【讨论】:

    • 所以我需要两个查询来获取两个状态的计数? @N。弗朗西斯
    • 你能分解一下你想要达到的目标吗?
    • 在一个查询中统计“是”和“否”的总状态
    • 您可以在您的视图中这样做,例如, 有不同的方法来实现一个目标,你可以使用其他方法。希望这有效
    【解决方案3】:

    简单地分组然后计数。

        $sql = "
            SELECT
                status,
                count(*) as count
            FROM
                TABLENAME
            GROUP BY
                status
        ";
    
        $query = $this->db->query($sql);
        return $query->result();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-18
      • 2020-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多