Zach
Zach

Reputation: 9721

Conditional Where clause if Left Join returns rows?

I feel like there is a way to do this using conditional Cases or Ifs, but I just can't figure it out.

The query below joins three tables together and works great if all three tables return rows. However, there are cases where records exist in campaign_groups and new_advertisers, but none in payment_transactions.

Because of the WHERE clause making sure the payment_transactions.transaction_date >= campaign_groups.date_created, rows with zero transactions are excluded.

Is there a way to apply the WHERE clause only when the LEFT JOIN returns rows?

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

Upvotes: 1

Views: 634

Answers (1)

Mark Byers
Mark Byers

Reputation: 838106

Move the condition into your ON clause:

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

Upvotes: 2

Related Questions