2017-09-21 105 views
1

我有兩個mysql表。 表:議案如何查詢兩個mysql表的一個字段的總和

id | billtype | amount | advid | paydate |adjid | adjdate | 
1 | electric | 10000 | 123 | 2017-01-01 | 50 | 2017-01-03 | 
2 | Water | 5000 | 124 | 2017-02-01 | 0 | 0000-00-00 | 
3 | Shirt | 500 | 125 | 2017-03-01 | 0 | 0000-00-00 | 

表:提前

id | advid | amount | balance | purpose | 
1 | 123 | 50000 | 20000 | Bill | 
2 | 124 | 70000 | 10000 | Bill | 
3 | 125 | 55000 | 15000 | Uniform | 
4 | 124 | 60000 | 10000 | Bill | 

我想創建一個下拉菜單,以便選擇哪些還沒有調整過的「提前」(adjid = 0和adjdate = 0000 -00-00)表:賬單和下拉菜單也將包含預先對相同提前ID(ADVID的合計值)象下面這樣:

<option>Bill-130000</option> 
<option>Uniform-55000</option> 

作爲總130000(70000 + 60000)的進步是德en對付預付ID 124,所以在Bill的情況下,Option菜單中的Advance總額應該是130000。但我沒能準確地計算出提前總量:

SELECT sum(a.amount), purpose FROM bill as b, advance as a WHERE b.paydate!='0000-00-00' AND b.adjid!=0 AND a.advid=b.advid GROUP BY a.advid 

在​​3210總額不來實際的。

什麼是適合此目的的查詢?

+0

你得到正確的結果。條件'b.paydate!='0000-00-00'AND b.adjid!= 0'只會給'bill'表中的'advid' = 123,因此只會給你50000. –

+0

通常,你會GROUP由您的SELECT中的非聚合列組成。 – Strawberry

回答

2

你可以嘗試

SELECT SUM(a.amount) AS amount, 
     MAX(purpose) AS purpose 
FROM advance a 
WHERE a.advid IN (
       SELECT b.advid 
       FROM bill b 
       WHERE b.paydate = '0000-00-00' 
         AND b.adjid = 0) 
GROUP BY a.advid 
+0

太棒了!感謝您的代碼。 –

相關問題