求和并联接多个MySQL表

时间:2018-12-10 02:20:15

标签: php mysql join sum

早上好,我有三个mysql表 transaction other_loan payment 。我想对表事务中的列 load_amount additional 求和,并将其对 other_loan 的列 amount 求和,然后减去到 payment 表中 payment_amount 列的总和。下面是我的代码:

$result = $db->query("
SELECT *
     , (sum(load_amount) + sum(additional) + sum(amount)) - sum(payment) as total 
  FROM transaction
     , other_loan
     , payment
  INNER JOIN client 
    ON client.id=transaction.id 
  INNER JOIN other_loan 
    ON other_loan.id=transaction.id 
  INNER JOIN payment 
    ON payment.id=transaction.id 
 INNER GROUP 
    BY client.id
  ");

这是我的桌子: transaction other_loan payment

我在表中显示结果,并且出现以下错误消息:

  

致命错误:未捕获错误:调用布尔值成员函数fetch_assoc()

请帮助。谢谢。

1 个答案:

答案 0 :(得分:0)

查询失败(因此$result为布尔值false),因为您两次对JOIN和表other_loanpayment进行了{{1} JOIN运算符,),而不给它们加上别名。我怀疑您实际上并不想这样做,而您的查询应该看起来像这样:

$result = $db->query("SELECT *, (SUM(load_amount) + SUM(additional) + SUM(amount)) - SUM(payment) as total 
                      FROM transaction
                      INNER JOIN client ON client.id=transaction.id 
                      INNER JOIN other_loan ON other_loan.id=transaction.id 
                      INNER JOIN payment ON payment.id=transaction.id
                      GROUP BY client.id");

我还怀疑load_amount实际上应该是loan_amount