duanjia3187 2018-09-26 21:17
浏览 86
已采纳

Codeigniter - 显示有条件的数字

I have Payment Table. This Payment Table has paymentCusId(It is Customer Id), paymentCredit and paymentDebit rows etc... How can I show, If Customer's Balance is less than 50 euros, I want to show how many customers balance less than 50 euros.

For example, 5 customers balance less than 50.

Can I solve this using sql query or php conditions ?

Code below:

$this->db->select('payment.paymentCusId, sum(paymentCredit) - sum(paymentDebit)');
$this->db->from('payment');
$this->db->where('sum(paymentCredit) - sum(paymentDebit) <', 50);

$query_debit =  $this->db->get();

$number = $query_debit->num_rows();

echo $number;

This code not working well. What can I do to show the number of customers less than 50 euros?

  • 写回答

1条回答 默认 最新

  • doushi3202 2018-09-27 00:53
    关注

    The query you are trying to perform has two errors.

    1 - In order to you functions that aggregate function you need to group the result using GROUP BY

    2 - Aggregation functions on the WHERE clause do not work, you need to put it in the having clause.

    For your case the correct query would be:

    $this->db->select('payment.paymentCusId, sum(paymentCredit) - sum(paymentDebit)');
    $this->db->from('payment');
    $this->db->group_by('payment.paymentCusId');
    $this->db->having('sum(paymentCredit) - sum(paymentDebit) <', 50);
    
    $query_debit = $this->db->get();
    
    $number = $query_debit->num_rows();
    
    echo $number;
    

    For more information about codeigniter query builder check their documentation

    A good way to figure out if your query is correct before trying to get results or num_rows, etc, is to verify it has an error:

        $error = $this->db->error();
        if($error) {
           echo $error['message'];
           echo $error['code'];
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 优质github账号直接兑换rmb,感兴趣伙伴可以私信
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)