2016-07-23 86 views
1

我有2張桌子。 t1t2Mysp Php Sum()乘法?

數據如下t1kid是planID,uid是用戶ID,buytime是購買量。

+---------+-------------+-------------+---------------+ 
| kid  | uid   | buytime1 | buytime2  | 
+---------+-------------+-------------+---------------+ 
| 1  | 1   | 10   | 5    | 
| 1  | 2   | 1   | 0    | 
| 1  | 3   | 3   | 5    | 
| 2  | 4   | 1   | 10   | 
| 3  | 5   | 20   | 6    | 
+---------+-------------+-------------+---------------+ 

t2數據:

+---------+-----------+-----------+ 
| ID  | costb1 | costb2 | 
+---------+-----------+-----------+ 
| 1  | 100  | 200  | 
| 2  | 300  | 500  | 
| 3  | 1000  | 2000  | 
+---------------------------------+ 

我願做SUM在MySQL一樣:

SUM buytime1 * costb1 + buytime2 * costb2 Where t1.kid = t2.id

$query = DB::query("SELECT SUM(something like buytime1 * costb1 + buytime2 * costb2) FROM ".DB::table('t1')." t1 LEFT JOIN ".DB::table('t2')." t2 ON (t1.kid = t2.id)"); 

所以最終的結果應該是40700

10 * 100 + 5 * 200 = 2000 
1 * 100 + 0 * 200 = 100 
3 * 100 + 5 * 200 = 1300 
1 * 300 + 10 * 500 = 5300 
20 * 1000 + 6 * 2000 = 32000 

那麼,我應該編輯我的編碼query

回答

2

只需使用sum您提供 - 這將導致40700:

select sum((t1.buytime1 * t2.costb1) + (t1.buytime2 * t2.costb2)) 
from t1 
    join t2 on t1.kid = t2.id 

不知道,如果你需要的outer join - 如果是這樣,那麼你需要定義那些缺失值應該相等。如果需要,使用​​3210雖然應該有幫助。