如何从1个表中的多行添加多个列以及从另一个表中添加1行?

时间:2014-08-19 21:03:07

标签: php mysql

我们将发票保存在一个名为invoices_v3的表中,并将付款保存在名为payments_v3的表中。每张发票完全可能有多笔付款。

SELECT *, 
SUM(invoices_v3.invoice_amount - payments_v3.pago_in_cash + payments_v3.pago_in_ccrd + payments_v3.pago_in_bnkd + payments_v3.pago_in_coup + payments_v3.pago_in_chek) AS end_balance 
FROM invoices_v3, payments_v3
WHERE payments_v3.invoice_no=invoices_v3.invoice_id AND invoices_v3.client_id = '$clean_id'
ORDER BY invoices_v3.invoice_id DESC

我试图让它从invoices_v3返回invoices_v3.client_id = '$clean_id'所有结果,并且在同一结果中,end_balance具有payments_v3.invoice_no=invoices_v3.invoice_id所有付款的总和。它现在正在做的只返回1个结果(仅限最后一个发票),其中end_balance具有与$ clean_id(客户端ID)匹配的所有付款的总和。

如果可能的话,我试图在没有JOINS的情况下这样做,因为这个脚本会经常被访问,而且一些客户ID可能有数百张发票,每张都有多笔付款。

修改

这是我尝试过的JOIN:

SELECT invoices_v3.*,
SUM(payments_v3.pago_in_cash + payments_v3.pago_in_ccrd + payments_v3.pago_in_bnkd + payments_v3.pago_in_coup + payments_v3.pago_in_chek) AS total_payments
FROM invoices_v3
LEFT JOIN payments_v3 ON invoices_v3.invoice_id=payments_v3.invoice_no
WHERE invoices_v3.client_id = '$clean_id'
AND payments_v3.old_invoice_no=invoices_v3.invoice_id <-- DELETE THIS LINE
GROUP BY invoices_v3.invoice_id
ORDER BY invoices_v3.invoice_id DESC

编辑2:

+----+-------------+-------------+------+----------------+----------------+---------+-------+--------+----------------------------------------------+
| id | select_type | table       | type | possible_keys  | key            | key_len | ref   | rows   | Extra                                        |
+----+-------------+-------------+------+----------------+----------------+---------+-------+--------+----------------------------------------------+
|  1 | SIMPLE      | invoices_v3 | ref  | inv_v1_cliente | inv_v1_cliente | 5       | const |     31 | Using where; Using temporary; Using filesort |
|  1 | SIMPLE      | payments_v3 | ALL  | NULL           | NULL           | NULL    | NULL  | 147706 |                                              |
+----+-------------+-------------+------+----------------+----------------+---------+-------+--------+----------------------------------------------+
2 rows in set (0.00 sec)

1 个答案:

答案 0 :(得分:0)

您应该在SQL

中添加GROUP BY子句

在您的COALESCE周围添加SUM对帐单,以确定帐单中没有现金付款

SELECT *, 
COALESCE(SUM(invoices_v3.invoice_amount - payments_v3.pago_in_cash + payments_v3.pago_in_ccrd + payments_v3.pago_in_bnkd + payments_v3.pago_in_coup + payments_v3.pago_in_chek),invoices_v3.invoice_amount) AS end_balance 
FROM invoices_v3, payments_v3
WHERE payments_v3.invoice_no=invoices_v3.invoice_id AND invoices_v3.client_id = '$clean_id'
GROUP BY invoices_v3.invoice_id
ORDER BY invoices_v3.invoice_id DESC

如果没有发票付款,将显示发票金额。