我有一个名为clients
的Mysql表。下面是哪种结构:
client_id conn_date monthly_bill
======================================
1 2016-08-18 100
2 2016-09-12 200
3 2016-10-20 250
4 2016-06-02 300
另一个名为client_bill_paid
的Mysql表。在此表中,我将client_id
与bill_month
一起插入(已支付哪个月的客户)
bill_id client_id bill_month
====================================
1 2 2016-10-01
2 3 2016-10-02
现在我在php中运行一个sql查询循环以获取所有客户端并希望每月的第一天生成一个帐单。
require_once("../header.php");
$query = mysqli_query($conn, "SELECT * FROM clients ");
echo "<table border='1'>";
echo "<tr>";
echo "<td>Client Id</td>";
echo "<td>Joined Date</td>";
echo "<td>Monthly Bill</td>";
echo "<td>Due</td>";
echo "<td>Paid</td>";
echo "</tr>";
while ( $result = mysqli_fetch_array($query) ) {
$client_id = $result['client_id'];
$conn_date = $result['conn_date']; // Joined Date
$monthly_bill = $result['monthly_bill'];
echo "<tr>";
echo "<td>$client_id</td>";
echo "<td>$conn_date</td>";
echo "<td>$monthly_bill</td>";
echo "<td> </td>"; // My question is here
echo "<td> </td>"; //
echo "</tr>";
}
echo "</table>";
现在,我希望在html 到期列之前显示到期金额,直到今天为止。
例如:
今天2017-01-18
和client_id
= 3 已加入2016-10-20
此客户尚未付款,因为没有client_id
= <在client_bill_paid
表中强> 3 。
所以现在这个客户的总应付金额应该是:
2016-10-20 = $88 // Joined 20th and month end 31th = 11 days * ( $250 / 31 )
2016-11-01 = $250
2016-12-01 = $250
2017-01-01 = $250
Total = $838
我想在html 到期列上显示 $ 838 。我怎样才能做到这一点 ?
答案 0 :(得分:0)
您可以在查询中使用LEFT JOIN - 类似:
$query = mysqli_query($conn, "SELECT c.*, count(p.id_client) as paid_months FROM clients c LEFT JOIN client_bill_paid p ON p.id_client = c.id_client") GROUP BY c.id_client;
所以 - 结果你将知道支付月数,然后你可以使用你的公式计算到期和支付金额。