views:

52

answers:

2

I have two tables Publishers and Campaigns, both have similar many-to-many relationships with Countries,Regions,Languages and Categories.

more info

Publisher2Categories has publisherID and categoryID which are foreign keys to publisherID in Publishers and categoryID in Categories which are identity columns. On other side i have Campaigns2Categories with campaignID and categoryID columns which are foreign keys to campaignID in Campaigns and categoryID in Categories which again are identities. Same goes for Regions, Languages and Countries relationships

How do I get campaignIDs of Campaigns that have at least one equal to Publisher (I pass to query publisherID) value from regions, countries, language or categories?

DB DIAGRAM

click here for direct link

thanks

+1  A: 

JOINING each individual manytomany table from publishers and campaigns and UNIONthe result should leave you with all campaignid's that have a match between publishers and campains through one of there respective relation tables.

SELECT  cc.CampaignID
FROM    dbo.PublisherSites2Countries pc
        INNER JOIN dbo.Campaings2Countries cc ON cc.CountryID = pc.CountryID
UNION SELECT pr.CampaignID
FROM    dbo.PublisherSites2Regions pr
        INNER JOIN dbo.Campaings2Regions cr ON cr.RegionID = pr.RegionID
...
Lieven
+1. If the CampaignID has to exist in all the four tables, use INTERSECT instead of UNION
Chris Bednarski
@Lieven, thanks. Finally you've got answer for me. I will check other answer performance versus your and decide which one executes faster with my data.Thanks again
eugeneK
*finally you've got answer for me?* That reads like *all other answers you've ever given are worthless*. (for the record, I do assume that's not what you meant ;)
Lieven
@Lieven, you are right. This is not what i've meant. I've meant that you asked me many times questions about my question but never gave an answer to any of my questions until now. You questions helped me to organize better questions and get better answers.Worthless answers are rare in here, mostly they exists because question is not understandable, at least in my case.
eugeneK
A: 

You probably want to find linked Campaigns and Publishers one join-type at a time, and union the results:

SELECT DISTINCT campaignID
  FROM Campaigns2Countries c2cy
 WHERE EXISTS (SELECT * FROM PublisherSites2Countries
                WHERE countryID = c2cy.countryID
                  AND publisherID = :publisherID)
UNION
SELECT DISTINCT campaignID
  FROM Campaigns2Categories c2cat
 WHERE EXISTS (SELECT * FROM PublisherSites2Categories
                WHERE categoryID = c2cat.categoryID
                  AND publisherID = :publisherID)
UNION
...
Marcelo Cantos
thanks, i will compare performance of this query against my db with other answer to see what performs better
eugeneK