返回MySQL中相同id组的最后一个插入行

时间:2015-08-09 04:28:38

标签: php mysql

我正在使用创建付款收据,我将支付一些金额,例如下面的例子

此已创建的收据但又有付款due_amount

cust_id   cust_name  invoice_id  paid_amount  due amount  makeapayment

1001       SAS              545      76           305          sasi 

这是我查询的结果 我必须支付到期金额100然后在支付相同的" id"之后创建另一行。查看新行旧行不查看只留在数据库中查看结果如下

cust_id   cust_name  invoice_id  paid_amount  due amount  makeapayment

1001       SAS              545       76           205          sasi   

目前我正在使用查询

SELECT pid, cust_id, cust_name, date, invoice_id, invoice_date, invoice_amount, paid_amount, paymentmade, makeapayment, due_amount, status FROM print_reciept
group by cust_id having due_amount!='0' ORDER BY pid DESC          

1 个答案:

答案 0 :(得分:0)

我想你可以试试这个

SELECT pid, cust_id, cust_name, date, invoice_id, invoice_date, invoice_amount, paid_amount, paymentmade, makeapayment, due_amount, status 
FROM print_reciept AS pr
INNER JOIN (
    SELECT MAX(pid) AS last_pid, cust_id
    FROM print_reciept
    GROUP BY cust_id
) AS tmp ON (tmp.cust_id = pr.cust_id AND tmp.last_pid > pr.pid)
GROUP BY cust_id 
ORDER BY pid DESC