count active-inactive-deleted结果

jjhzyzn0  于 2021-06-21  发布在  Mysql
关注(0)|答案(3)|浏览(396)

我试图计算mysql数据库中显示给用户的活动结果的数量,但我只能计算行的数量,但我似乎无法计算有多少活动/非活动/删除的

<?php
  $user_id = $this->session->userdata('user_id');
  $query = $this->custom_query("SELECT post_status FROM listings WHERE user_id=$user_id ");
  if($query->num_rows()>0){
    foreach($query->result() as $row){
      if($row->post_status == 'active'){
        echo $row->num_rows();
      }
    }                   
  }
?>
ct3nt3jp

ct3nt3jp1#

您可以使用修改过的sql语句来尝试此修改过的代码。
一个查询中有多个计数。

<?php
      $user_id = $this->session->userdata('user_id');

      $query = $this->custom_query("SELECT 
          COUNT(CASE WHEN post_status = 'active' THEN 1 END) as active_total,
          COUNT(CASE WHEN post_status = 'inactive' THEN 1 END) as inactive_total,
          COUNT(CASE WHEN post_status = 'deleted' THEN 1 END) as deleted_total
        FROM listings WHERE user_id = $user_id");

        $row = $query->result();

        echo "Active: ".$row[0]->active_total."<br/>\n";
        echo "Inactive: ".$row[0]->inactive_total."<br/>\n";
        echo "Deleted: ".$row[0]->deleted_total."<br/>\n";
?>
pu3pd22g

pu3pd22g2#

您可以使用sql count函数,在这里查看count函数的工作原理https://www.w3schools.com/sql/sql_count_avg_sum.asp
寻找答案;

select count(id) as active_count from listings WHERE user_id=$user_id and post_status = 'active'
zrfyljdw

zrfyljdw3#

计算检索到的数据库记录的简单方法是 num_rows 你的问题

$user_id = $this->session->userdata('user_id');
return $this->db->get_where('listings', array('user_id'=> $user_id, 'post_status' => 'active'))->num_rows();

相关问题