0

我有以下查询,没有,SUM(amount) AS total它可以正常工作。现在的问题是我想从我的表中选择所有值,vouchers同时想amount从我的另一个表中获取字段的总和值details

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)

我尝试了上面的查询,但它显示了以下错误。(请检查链接)

http://i44.tinypic.com/bdaq.png

4

1 回答 1

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已经包含一个经过清理和边界检查的值

于 2012-04-07T19:52:45.647 回答