softcr
softcr

Reputation: 620

MySQL condition on joined data

I have two tables "customers" and "campaigns":

    customers
    -------------
    id   | int
    -------------
    name | varchar 


    campaigns
    ----------------------
    id           | int
    ----------------------
    customers_id | int
    ----------------------
    name         | varchar

A customer can have multiple campaigns. The association between the two tables is via campaigns.customers_id = customers.id. Now I want to get all customers that have gotten campaign with name "A" and name "B".

I tried a JOIN with an IN statement, but it returns all customers, that have received any of campaign "A" or "B":

    SELECT
      customers.name
    FROM
      customers
    JOIN
      campaigns
    ON
      customers.id=campaigns.customers_id
    WHERE
      campaigns.name IN('A','B')

Thanks a lot!

Upvotes: 2

Views: 74

Answers (3)

carexcer
carexcer

Reputation: 1427

SELECT
  customers.name
FROM
  customers
LEFT JOIN campaigns c1 ON customers.id=c1.customers_id and c1.name = 'A'
LEFT JOIN campaigns c2 ON customers.id=c2.customers_id and c2.name = 'B'

With the first LEFT JOIN you will get the customers that have campaigns and the campaign names are 'A', and then the result will join with the campaigns whose have name 'B'.

Only the rows with campaign.name = A and campaign.name = B will be selected.

Upvotes: 0

Sabari
Sabari

Reputation: 73

You have joined campaigns table with customers.id=campaigns.id instead of customers.id=campaigns.customers_id.

Correct Query is

SELECT
      customers.name
    FROM
      customers
    JOIN
      campaigns
    ON
      customers.id=campaigns.customers_id
    WHERE
      campaigns.name IN('A','B')

This should work :)

Upvotes: 1

Richard
Richard

Reputation: 30618

You'll need to join for each campaign

SELECT
  customers.name
FROM
  customers
INNER JOIN campaigns c1 ON customers.id=c1.id and c1.name = 'A'
INNER JOIN campaigns c2 ON customers.id=c2.id and c2.name = 'B'

This will now contain customers who have received both.

Upvotes: 0

Related Questions