简体   繁体   English

选择所有值并同时从不同表中总结一个字段的值

[英]Selecting all values and sum up a field's value from different table at the same time

I have the following query, without the ,SUM(amount) AS total it works fine.我有以下查询,没有,SUM(amount) AS total它工作正常。 Now the problem is I want to select all the values from my table vouchers and at the same time want to get the sum value of the field amount from my another table called details .现在的问题是我想要 select 我的表vouchers中的所有值,同时想要从我的另一个名为details的表中获取字段amount的总和值。

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)

I tried the above query but it showed me the following error.(pls check the link)我尝试了上面的查询,但它显示了以下错误。(请检查链接)

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

Place the details sum into a subquery, against which you LEFT JOIN .details总和放入一个子查询中,您LEFT JOIN将对其进行处理。 Your original was missing any GROUP BY clause for your SUM() aggregate.您的原件缺少SUM()聚合的任何GROUP BY子句。

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)

( We assume $code contains a sanitized and bounds-checked value already ) 我们假设$code已经包含经过清理和边界检查的值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM