条件Where子句,如果Left Join返回行?

时间:2012-04-19 22:19:35

标签: mysql left-join where-clause conditional-statements

我觉得有一种方法可以使用条件Case或Ifs来做到这一点,但我无法理解。

下面的查询将三个表连接在一起,如果所有三个表都返回行,则效果很好。但是,有些情况下,campaign_groups和new_advertisers中存在记录,而payment_transactions中没有记录。

由于WHERE子句确保payment_transactions.transaction_date> = campaign_groups.date_created,因此排除了零事务的行。

有没有办法只在LEFT JOIN返回行时应用WHERE子句?

SELECT sum(payment_transactions.transaction_amount) as payment, 
            new_advertisers.account_id, 
            new_advertisers.advertiser_id,
            max(payment_transactions.transaction_date) as last_payment,
            campaign_groups.id,
            campaign_groups.date_created,
            TIMESTAMPDIFF(DAY, max(payment_transactions.transaction_date), NOW()) as days_passed
        FROM campaign_groups
        INNER JOIN new_advertisers ON campaign_groups.advertiser_id = new_advertisers.advertiser_id
        LEFT JOIN payment_transactions ON payment_transactions.account_id = new_advertisers.account_id
        WHERE payment_transactions.transaction_date >= campaign_groups.date_created
            AND campaign_groups.weekly_budget_cents > 0
        ORDER BY days_passed DESC

1 个答案:

答案 0 :(得分:2)

将条件移动到ON子句中:

LEFT JOIN payment_transactions
    ON payment_transactions.account_id = new_advertisers.account_id
    AND payment_transactions.transaction_date >= campaign_groups.date_created
WHERE campaign_groups.weekly_budget_cents > 0