数据库中三个不同表之间的计算?

时间:2017-09-01 07:16:18

标签: php mysql codeigniter

我是编程的初学者。我需要快速支持。

数据库中有三个表,(tblclientstblinvoicestblinvoicepaymentrecords)。

现在点是 - 我想在客户区显示总到期,现在只有百分比图显示。

以下是Flow:

  1. 我添加了一个客户端,它位于tblclients,客户端ID为1。

  2. 我为客户ID 1创建10000的发票,它将在tblinvoices中记录相应列中的ID,总金额和客户ID(id,total和clientid)。< / p>

  3. 现在我将记录此发票的付款,客户仅支付7000 - 此付款将记录在tblinvoicepaymentrecords中,已支付金额和发票ID在各栏(amount和{{ 1}})。

  4. 所以,现在我想在他们登录他们的客户面板时显示客户,总金额到期。 (就像每个客户他们自己的到期一样)。

    任何支持它将拯救我一整天,它会让我无压力。

    我将把这个包括在我要展示的地方。 在下面找到表格结构 Table Structrure

1 个答案:

答案 0 :(得分:1)

enter image description here

希望这有助于你......

SELECT
    client.name AS client_name,
    tblinvoices.total_amount AS total_amount,
    tblinvoicepaymentrecords.amount_paid AS paid_amount,
    (
        tblinvoices.total_amount - tblinvoicepaymentrecords.amount_paid
    ) AS amount_due
FROM
    client
LEFT JOIN tblinvoices ON client.id = tblinvoices.client_id
LEFT JOIN tblinvoicepaymentrecords ON tblinvoices.invoice_id = tblinvoicepaymentrecords.invoiceid

这是我得到的结果。

enter image description here

根据您的表格结构这将是您的查询

SELECT 
tblclients.userid as client_id, 
    tblclients.company as company_name, 
        tblinvoices.total AS total_amount, 
            tblinvoicepaymentrecords.amount AS paid_amount, 
                ( tblinvoices.total - tblinvoicepaymentrecords.amount ) AS amount_due 
            FROM 
            tblclients 
            LEFT JOIN tblinvoices ON tblclients.userid = tblinvoices.clientid 
            LEFT JOIN tblinvoicepaymentrecords ON tblinvoices.id = tblinvoicepaymentrecords.invoiceid