简体   繁体   中英

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!

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 :)

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM