我有以下查询,没有,SUM(amount) AS total
它可以正常工作。现在问题是我想从我的表vouchers
中选择所有值,同时想要从另一个名为amount
的表中获取字段details
的总和值。 / p>
SELECT *,SUM(amount) AS total FROM vouchers
LEFT JOIN details on vouchers.voucher_no = details.voucher_no
LEFT JOIN accounts on accounts.code = vouchers.account_code
WHERE (voucher_type='1' AND t_code=$code)
我尝试了上面的查询,但它向我显示了以下错误。(请查看链接)
答案 0 :(得分:1)
将details
和放入子查询中,LEFT JOIN
对应子查询。您的原始广告缺少GROUP BY
汇总的SUM()
条款。
SELECT
vouchers.*,
/* from the subquery... */
detailssum.total
FROM
vouchers
LEFT JOIN (
/* Subquery gets total per voucher_no to join against vouchers */
SELECT voucher_no, t_code, SUM(amount) as total FROM details GROUP BY voucher_no
) detailssum ON vouchers.voucher_no = detailssum.voucher_no
LEFT JOIN accounts on accounts.code = vouchers.account_code
WHERE (voucher_type='1' AND t_code=$code)
(我们假设$code
已经包含已清理和边界检查的值)