2014-02-19 203 views
0

我有這樣的查詢運行得很好:MYSQL GROUP BY和WHERE子句

SELECT offers.*, COALESCE(SUM(commission),0) AS revenue, COUNT(commission) AS leads 
FROM offers 
LEFT JOIN offers_revenue AS or ON or.offerid=offers.offerid 
GROUP BY offers.offerid 

這將返回我的所有與正確comission報價表中的行相加。

現在我需要添加一個WHERE子句(可以說,當某個條件滿足並不總和):

SELECT offers.*, COALESCE(SUM(commission),0) AS revenue, COUNT(commission) AS leads, reversed 
FROM offers 
LEFT JOIN offers_revenue AS or ON or.offerid=offers.offerid 
WHERE reversed=0 
GROUP BY offers.offerid, reversed 

開始我嘗試只需添加WHERE子句,但是這回我一個空集的結果,挖掘後我知道,你需要包括你的GROUP BY參數,並將它們包括在SELECT中,但仍然沒有結果。

我在這裏做錯了什麼?在第一個查詢中,我測試表上的所有結果都被設置爲reverse = 0,所以我必須在這裏丟失一些東西。

+1

'WHERE逆轉= 0' ==>'具有相反= 0'編輯:組後添加BY .. .... –

+0

HAVING沒有做的伎倆。 –

回答

2

想必reversed是在or表。您通過比較將left outer join變成inner join。該解決方案是將條件移到on條款:

SELECT o.*, COALESCE(SUM(ofr.commission),0) AS revenue, COUNT(ofr.commission) AS leads, reversed 
FROM offers o LEFT JOIN 
    offers_revenue ofr 
    ON `ofr`.offerid = o.offerid and ofr.reversed = 0 
GROUP BY o.offerid; 
+0

啊!這是我想的首選方式,謝謝! –

2

嘗試這與IF statment:

SELECT offers.*, if(reversed=0 , 0 , SUM(commission))) AS revenue, 

     COUNT(commission) AS leads, 
     reversed     
FROM offers 
LEFT JOIN offers_revenue AS or ON or.offerid=offers.offerid 
GROUP BY offers.offerid, reversed 
+0

「你的SQL語法錯誤」(是的,帶走了你的評論) –

+0

ahh對不起,我忘了'''現在試試 –

+0

@echo_Me小異議如果不是語句,它是一個函數,是'IF(a, b,c)'是一個陳述。 –