MySQL select语句中的SUM递增

时间:2017-08-02 13:54:26

标签: mysql

我有这个SQL:

SELECT                      
SUM(er.total)    
AS total
FROM    
campaigns AS cmp    
JOIN versions AS cv ON (cv.campaign_id = cmp.id)
JOIN creatives AS cr ON (cr.version_id = cv.id)
JOIN records AS er ON (er.creative_id = cr.id)
WHERE    
cmp.business_id IN (-1,'39909') AND
cv.campaign_id IN (-1,65288) AND
er.type IN (5,6,1) AND    
er.date BETWEEN '2017-06-11' AND '2017-06-11'    
GROUP BY version_id, er.date

我需要在where子句中添加一个新条件,它需要添加新的连接,如下所示 -

    SELECT                      
    SUM(er.total)    
    AS total
    FROM    
    campaigns AS cmp
    JOIN products as p ON (p.campaign_id = cmp.id)
    JOIN versions AS cv ON (cv.campaign_id = cmp.id)
    JOIN creatives AS cr ON (cr.version_id = cv.id)
    JOIN records AS er ON (er.creative_id = cr.id)
    WHERE    
    cmp.business_id IN (-1,'39909') AND
    cv.campaign_id IN (-1,65288) AND
    er.type IN (5,6,1) AND    
    er.date BETWEEN '2017-06-11' AND '2017-06-11' AND
    p.product_id IN(1,2)
    GROUP BY version_id, er.date

但是,在这里,SUM(er.total)的值会发生变化,会增加。我尝试添加左/右/内连接。但结果是一样的。如何在不增加总计的情况下为此表添加连接?

1 个答案:

答案 0 :(得分:0)

SELECT                      
    SUM(er.total)    
    AS total
    FROM    
    campaigns AS cmp
    JOIN products as p ON (p.campaign_id = cmp.id and p.product_id IN(1,2))
    JOIN versions AS cv ON (cv.campaign_id = cmp.id)
    JOIN creatives AS cr ON (cr.version_id = cv.id)
    JOIN records AS er ON (er.creative_id = cr.id)
    WHERE    
    cmp.business_id IN (-1,'39909') AND
    cv.campaign_id IN (-1,65288) AND
    er.type IN (5,6,1) AND    
    er.date BETWEEN '2017-06-11' AND '2017-06-11' AND

    GROUP BY version_id, er.date

尝试以上查询。

这里我更改了条件ON子句而不是WHERE子句。