从数据库中获取值

时间:2016-10-29 09:52:37

标签: mysql codeigniter-3

这是我名单中的数据名为rent

    id    date     stud_id  paid    balance

    18  10-2016       94    15000   15000
    19  10-2016       94    10000   5000
    20  10-2016       96    25000   5000
    21  10-2016       96    5000    0

这里我希望得到最后一个插入的stud_id平衡,但我得到了第一个。 我的代码看起来像这样

public function rent_outstanding($hos,$dt)
{
    $this->db->select('student_hostel.*,rent.balance,rent.paid');
    $this->db->join('rent','rent.stud_id=student_hostel.id');
    $this->db->where('status!=','G');
    $this->db->where('status!=','R');
    $this->db->where('hostel',$hos);
    $this->db->where('rent.date',$dt);
    $this->db->select_sum('paid');
    $this->db->group_by('stud_id');
    $query=$this->db->get('student_hostel');
    return $query;
}

我的student_hostel表看起来像这样

     id   first_name  last_name    stud_id     admit_date   hostel   class  room bed status

     94     ss        ff          PHBH00094     01-10-2016   12        16   115  501A    P
     96    maltu      uv          PHBH00096     01-10-2016   12        16   115  501C    p

我的结果是这样的

SI.No   STUDENT ID   NAME    RENT    PAID    BALANCE
 1      PHBH00094     Ss    30000   25000    15000  
 2      PHBH00096    Maltu  30000   30000    5000   

我希望得到这样的结果

SI.No   STUDENT ID   NAME    RENT    PAID    BALANCE
 1      PHBH00094     Ss    30000   25000    5000   
 2      PHBH00096    Maltu  30000   30000    0  

1 个答案:

答案 0 :(得分:1)

您需要在某处指定从租借表中获取最大ID。 这个查询应该给你。

In [38]: [np.mean(i) for i in a]
Out[38]: [1.5, 4.0]

如果您需要该日期的余额select stud_id ,first_name, paid, balance from rent rt, student_hostel s where hostel='$hosr' and ent.date='$dt' and id = (select max(id) from rent r where r.stud_id = rt.stud_id) and status!= 'G' and status!= 'R'

,请在内部查询中添加日期

对于Codeignitor,您可以直接编写查询:

id = (select max(id) from rent r where r.stud_id = rt.stud_id and r.date='$dt')

此处有更多信息:https://www.codeigniter.com/userguide3/database/queries.html#query-bindings

相关问题