2016-04-10 42 views
0

我有兩個MySQL查詢:如何查詢的兩個型動物MySQL表,並比較結果

1:

select TblC.name, 
SUM(TblC.total) as Sum 
from TblC 
left join TblCli on TblC.id_cli = TblCli.id 
group by TblCli.name asc 

結果是

NAME  SUM 
john 1000 
peter 500 
Alicia 300 

2:

select TblCli.name, 
SUM(TblRec.total) as Pay 
from TblRec 
left join TblCli on TblRec.id_cli = TblCli.id 
group by TblCli.name asc 

結果是

NAME Pay 
john 500 
peter 100 

有兩種不同的表沒有直接關係 我需要加入這兩個查詢,並得到這樣的結果:

NAME  SUM PAY Difference 
john  1000 500   500 
peter  500 100   400 
Alicia 300 0   300 

我如何執行?

回答

0

以下應該工作。演示與您的數據:http://sqlfiddle.com/#!9/ba6264/6

我強烈建議你做的TblCli.id而不是TblCli.name

select A.name, sum , IFNULL(pay,0) as pay, (sum - IFNULL(pay,0)) Difference FROM 
    (select TblC.name, 
    SUM(TblC.total) as Sum 
    from TblC 
    left join TblCli on TblC.id_cli = TblCli.id 
    group by TblCli.name) A 
LEFT JOIN 
    (select TblCli.name, 
    SUM(TblRec.total) as Pay 
    from TblRec 
    left join TblCli on TblRec.id_cli = TblCli.id 
    group by TblCli.name) B 
ON A.name = B.name; 
+0

拉胡爾加入,你的回覆是優秀的,偉大的作品。真的感謝。 –

+0

太好了。如果你喜歡,請接受答案 – Rahul