2013-06-18 108 views
1

總和我有兩個表增加了兩個獨立的表

td_sell

|----------|----------------|------------------| 
| id  | user_id  | price   | 
|----------------------------------------------| 
| 1  |  2   |  10   | 
|----------------------------------------------| 
| 2  |  1   |  5   | 
|----------------------------------------------| 
| 3  |  2   |  3   | 
|----------------------------------------------| 

和td_commsion

|----------|----------------|------------------| 
| id  | user_id  | price   | 
|----------------------------------------------| 
| 1  |  1   |  3   | 
|----------------------------------------------| 
| 2  |  1   |  5   | 
|----------------------------------------------| 
| 3  |  2   |  3   | 
|----------------------------------------------| 
現在

我想要一個SQL查詢這樣

SELECT (SUM(td_sell.price) + SUM(td_comission.price)) AS his_earning 
FROM td_sell, td_comission 
WHERE td_sell.user_id='1' 
AND td_comission.user_id='1' 

但它顯示異常結果

結果應該是13,但其顯示29

+1

您正在錯誤地加入表格。閱讀http://dev.mysql.com/doc/refman/5.0/en/join.html以獲得更多關於如何使用連接的信息。 –

+1

btw你有錯別字:請參閱td_coMMision –

回答

0
SELECT sum(price) 
FROM (
    SELECT * FROM td_sell 
    UNION ALL 
    SELECT * FROM td_commission 
) a 
where a.user_id=1 

這裏有一個SQL小提琴: Fiddle

1

這將工作:

SELECT (SELECT SUM(s.price) FROM td_sell s WHERE s.user_id = 1) 
+ 
(SELECT SUM(c.price) FROM td_comission c WHERE c.user_id = 1) 

DEMOSqlFiddle

0

在合併結果之前,您需要分別在每張桌子上完成總和。以下是一種方法:

select (sell + commission) as his_earning 
from (select SUM(td_sell.price) as sell 
     from td_sell 
     where td_sell.user_id='1' 
    ) s cross join 
    (select SUM(td_comission.price) as commission 
     from td_comission 
     where td_comission.user_id='1' 
    ) c