查询多个连接和求和函数给出错误的总数或总和

时间:2012-10-14 16:10:14

标签: mysql join sum

发布查询检索所有相关字段,但 SUM(af_py_commission) 函数导致问题,并且只是在结尾处添加额外的零,然后在右端添加。

e.g。如果答案是45,它将给出450并且该字段的数据格式是浮动的,否则这个查询工作正常....

我尝试在同一个字段上使用相同功能的简单查询,但没有连接,所以它工作正常并给出正确的ans。任何人都可以帮助我在这个> ??

中做错了
SELECT f.af_id AS af_if
   , aff_cust_tbl.af_id AS cu_af_id
   , aff_payment_tbl.af_cust_id AS pym_cus_id
   , SUM(af_py_commission)
FROM aff_tbl AS f
INNER JOIN aff_tbl ON f.af_id = 2
INNER JOIN aff_cust_tbl ON aff_cust_tbl.af_id = 2
INNER JOIN aff_payment_tbl ON aff_payment_tbl.af_id = 2;

2 个答案:

答案 0 :(得分:2)

内连接错误

试试这个:

SELECT
f.af_id                    AS af_if,
aff_cust_tbl.af_id         AS cu_af_id,
aff_payment_tbl.af_cust_id AS pym_cus_id,
SUM(af_py_commission)
FROM aff_tbl AS f
INNER JOIN aff_tbl as f2
ON f.af_id = 2 AND f2.af_id=2
INNER JOIN aff_cust_tbl
ON aff_cust_tbl.af_id = 2
INNER JOIN aff_payment_tbl
ON aff_payment_tbl.af_id = 2;

编辑的行是

 INNER JOIN aff_tbl as f2
 ON f.af_id = 2 AND f2.af_id=2

试试这个:

SELECT f.af_id                    AS af_if, 
       aff_cust_tbl.af_id         AS cu_af_id, 
       aff_payment_tbl.af_cust_id AS pym_cus_id, 
       Sum(af_py_commission) 
FROM   aff_tbl AS f 
       INNER JOIN aff_cust_tbl 
               ON f.af_id = aff_cust_tbl.af_id 
       INNER JOIN aff_payment_tbl 
               ON aff_payment_tbl.af_id = aff_cust_tbl.af_id 
WHERE  f.af_id = 2; 

如果它没有给出正确的结果,请尝试在此处进行总结和后期分析......

答案 1 :(得分:0)

如果使用聚合函数,可能缺少GROUP BY子句。试试这个:

SELECT
f.af_id                    AS af_if,
aff_cust_tbl.af_id         AS cu_af_id,
aff_payment_tbl.af_cust_id AS pym_cus_id,
SUM(af_py_commission)
FROM aff_tbl AS f
INNER JOIN aff_tbl
ON f.af_id = 2
INNER JOIN aff_cust_tbl
ON aff_cust_tbl.af_id = 2
INNER JOIN aff_payment_tbl
ON aff_payment_tbl.af_id = 2;
GROUP BY f.af_id