$stmt = "insert into {CI}payment_logs (customer_id, invoice_id, invoice_total_amount, invoice_paid_amount, customer_paid_amount, invoice_payment_on ) "
. "values( ?, ?, ?, ?, ?, NOW() )";
$this->db->query( $stmt, array( $Customer_Id, $Invoice_Id, $Invoice_Total_Amount, $Deducted_Amount, $Paid_By_Cust ) );
$Log_Id = $this->db->insert_id(); // Returns Last Insert ID
根据我的需要,这是正常工作,但我必须在特定条件下更新同一个表中每一行的状态。看看图片,
这是上述查询的插入数据。正如您在invoice_total_amount
中看到的那样是总金额,但是这个数量在第三行数据中完成。在高亮点数量SUM等于invoice_status
之后,我必须将paid
字段更新为invoice_total_amount
,在其余字段中,我必须将状态更新为partial
。我尝试更新状态以添加触发器但不成功。
然后我尝试使用此命令使用PHP。
update {CI}payment_logs
set invoice_status = IF( invoice_total_amount = sum(invoices_paid_amount), 'paid', 'partial' )
where log_id = ?
但我没有得到invoices_paid_amount
的SUM,其中invoice_id = 5
,我尝试在IF条件下使用子查询,但它无效我的查询。
请帮我解决一下查询或触发解决方案..
答案 0 :(得分:4)
加入计算总和的子查询。
UPDATE {CI}payment_logs l1
JOIN (SELECT invoice_id, SUM(invoices_paid_amount) total
FROM {CI}payment_logs
GROUP BY invoice_id) l2
ON l1.invoice_id = l2.invoice_id
SET invoice_status = IF(invoice_total_amount = total, 'paid', 'partial')
WHERE log_id = ?