要获取的上一行值 [英] Previous row value to be fetched
问题描述
在这里,我想将上一行的余额值输入到我的字段中。
Here I want to get the previous row balance value in to my field.
customer_id'16'的余额的最后一个ID是200,但我想将先前的id值获取到字段中,这就是我的表
The last id of customer_id '16' of balance is 200, but I want to get the previous ids value in to the field and this is my table
id order_id customer_id amount actual_amount paid_amount balance type
25 11 16 100.00 50.00 50.00 Cash
26 12 16 200.00 100.00 100.00 Cash
27 13 16 150.00 100.00 50.00 Cash
28 14 16 300.00 250.00 50.00 Cash
29 14 16 170.00 100.00 70.00 Cash
30 15 16 100 170.00 70.00 100.00 Cash
31 16 16 400 500.00 300.00 200.00 Cash
这是我的模型
public function order_balance($order_code)
{
$this->db->join('services','payment.customer_id=services.customer_id','left');
$this->db->select('payment.*,payment.balance,payment.actual_amount,payment.customer_id');
$this->db->order_by('payment.id','desc');
$query = $this->db->get_where('payment',array('code' => $order_code));
return $query->previous_row();
}
这是我的控制权
public function final_payment($order_code)
{
$data['active_mn']='';
$data['result'] = $this->Account_model->order_balance($order_code);
$this->load->view('final_payment',$data);
}
我的服务表如下:
id code customer_id particulars
11 ORD00011 16 phone
12 ORD00012 16 gdf
13 ORD00013 16 ghgfh
14 ORD00014 16 tv
15 ORD00015 16 ghfg
16 ORD00016 16 tv
17 ORD00017 16 gdfg
18 ORD00018 16 desk
19 ORD00019 16 gdf
我的结果应该是这样的:
My result should be like this:
id order_id customer_id amount actual_amount paid_amount balance type
31 16 16 400 500.00 300.00 100.00 Cash
推荐答案
这里的一个选择是使用<$ c自连接$ c> payment 表,并连接到 customer_id
和 order_id
列。您可以添加另一个join函数调用,然后在选择的结果中使用它。以下解决方案使用原始查询,因为Codeigniter在连接条件下似乎不容许算术运算:
One option here would be to do a self join with the payment
table, joining on the customer_id
and order_id
columns. You can add another join function call and then use the result in your select. The following solution uses a raw query since Codeigniter does not seem to tolerate arithmetic in the join condition:
public function order_balance($order_code)
{
$this->db->query("SELECT p1.*, p2.balance AS previous_balance FROM payment p1 INNER JOIN payment p2 ON p1.order_id = p2.order_id + 1 AND p1.customer_id = p2.customer_id LEFT JOIN services s ON p1.customer_id = s.customer_id ORDER BY p1.id DESC");
$query = $this->db->get_where('p1', array('code' => $order_code));
return $query->previous_row();
}
查询的格式为:
SELECT p1.*, p2.balance AS previous_balance
FROM payment p1 INNER JOIN payment p2
ON p1.order_id = p2.order_id + 1 AND
p1.customer_id = p2.customer_id
LEFT JOIN services s
ON p1.customer_id = s.customer_id
ORDER BY p1.id DESC
这篇关于要获取的上一行值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!