2013-07-20 49 views
1

下面是表使用雙左的加入在查詢返回的值不同

表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

問題是,每個連接是1 - 許多,所以你乘以每個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