【问题标题】:how to get sum of a column with codeigniter query [duplicate]如何使用codeigniter查询获取列的总和[重复]
【发布时间】:2019-12-07 07:29:20
【问题描述】:

我正在尝试使用 codeigniter 查询作为 mysql 表中的列值的总和

$this->db
     ->query("Select SUM(tb1.amount) from table1 tb1 inner join table2 tb2 on tb2.Id=tb1.Id Where tb2.Status='1'")
     ->result()

它给了我array to string conversion这样的错误我只需要一个像count(amount) returns number of rows with num_row()这样的数字

【问题讨论】:

    标签: php mysql codeigniter


    【解决方案1】:

    你可以使用codeigniter的select_sum()函数。试试下面的代码-

    $query = $this->db->select_sum("tb1.amount")
                      ->from("table1 as tb1")
                      ->join("table2 as tb2","tb1.id = tb2.id") 
                      ->where("tb2.status",1)
                      ->get();
    $query = $query->result();
    

    $query = $this->db->query('SELECT sum(tb1.amount) FROM table1 as tb1 join table2 as tb2 on tb1.id = tb2.id where tb1.status = 1'); $query = $query->result_array();

    【讨论】:

      【解决方案2】:

      如果您想获得单行,请使用 row() 而不是 result

      $data = $this->db
           ->query("Select SUM(tb1.amount) as total from table1 tb1 inner join table2 tb2 on tb2.Id=tb1.Id Where tb2.Status='1'")
           ->row()
      

      获取数据。

      echo $data->total;
      

      【讨论】:

        【解决方案3】:

        用作 => $data['total']

        $data = $this->db
             ->query("Select SUM(tb1.amount) as total from table1 tb1 inner join table2 tb2 on tb2.Id=tb1.Id Where tb2.Status='1'")
             ->row_array()
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-05-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-14
          • 1970-01-01
          相关资源
          最近更新 更多