我有这个运行得很好的查询:
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
这将返回商品表中的所有行,并添加了正确的商品。
现在我需要添加一个where子句(比方说,当满足某个条件时不要SUM):
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中包含where参数并将它们包含在SELECT ...中但是仍然没有结果。
我在这里做错了什么?在第一个查询中,我的测试表上的所有结果都设置为reverse = 0,所以我必须在这里遗漏一些东西。
答案 0 :(得分:2)
尝试使用IF语句:
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
答案 1 :(得分: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;