我怎样才能在第二张桌子上获得最新的付款日期?

时间:2017-04-25 02:27:40

标签: php mysql mysqli

这是我当前的查询

$ sql =" SELECT full_nameamount,                  SUM(paymentspayment_amount)为totalPayment,                  borrowersamount - SUM(paymentspayment_amount)为totalBalance,                  date_borrowedborrowersid                  来自borrowers                   LEFT JOIN payments点击borrowersid = paymentsborrower_id                   GROUP BY borrowersid ORDER BY date_borrowed DESC";

第一张桌子; enter image description here

第二张表; enter image description here

我的桌子; enter image description here

1 个答案:

答案 0 :(得分:1)

联接将为您提供所有付款记录,您只需要最后一个。做一个子查询:

$sql = "SELECT 
   full_name, amount, SUM(payments.payment_amount) as totalPayment,
   borrowers.amount - SUM(payments.payment_amount) as totalBalance, 
   date_borrowed, borrowers.id,
   (SELECT payment_date FROM payments 
       WHERE borrowers.id=payments.borrower_id 
       ORDER BY payment_date DESC LIMIT 0,1) 
       AS last_payment
    FROM borrowers GROUP BY borrowers.id ORDER BY date_borrowed DESC";