在查询中使用双左连接会返回不同的值

时间:2013-07-20 00:22:29

标签: mysql function

以下是表格

表1

CREATE TABLE table1 (
id smallint(5) NOT NULL AUTO_INCREMENT primary key,
name varchar(30) NOT NULL
 )
ENGINE=InnoDB;

表2

create table table2(
no int auto_increment primary key,
Reg_no  varchar(2),
debit decimal(19,2)
)
engine=innodb;

表3

 create table table3(
 no int auto_increment primary key,
 Reg_no  varchar(2),
 Paid decimal(19,2)
)
engine=innodb;

以下是我的查询代码。

SELECT id, sum(Paid) AS AMOUNT,sum(debit) AS DEBIT 
from table1 LEFT JOIN table2 ON table1.id=table2.Reg_no
LEFT JOIN table3 ON table1.id=table3.Reg_no 
GROUP BY table1.id

请问我发现在查询中使用双左连接非常困难,此代码中的问题是,上面查询中使用的总和超出预期数字,例如sum(10+10)将输出40而不是20。请问我的代码在哪里出错。如果有人能帮助我,我将不胜感激。谢谢你提前

1 个答案:

答案 0 :(得分:1)

问题是每个连接都是1-many所以你要将每个id的行数相乘。

解决方案是预先汇总结果。但是,您没有在问题中提供足够的信息来给出正确的答案。查询可能看起来像:

SELECT id, Paid, Debit
from table1 LEFT JOIN
     (select Reg_no, sum(Debit) as Debit
      from table2
      group by Reg_no
     ) table2
     ON table1.id = table2.Reg_no left outer join
     (select Reg_no, sum(Paid) as Paid
      from table3
      group by Reg_no
     ) table3
     ON table1.id = table3.Reg_no 
order BY table1.id