views:

34

answers:

1

I'm still a neophyte when it comes to SQL queries, so I was hoping someone could lend me a hand.

Assume I have 3 tables, Skill, Set, and Contact, and 2 linking tables, SkillSet and ContactSet. (the 3 tables have an "ID" column that is being used as a primary key)

Contacts can have any number of sets, and vice versa (many-to-many)

Sets can have any number of skills, and vice versa (also many-to-many)

What I want is, when presented with a skill's ID, to return every contact with a set containing that skill.

Still with me?

Here's what I've got so far:

SELECT        Set.ID as expr1
FROM SkillSet
WHERE Skill.ID = @SkillID
//this selects every set containing the Skill.


SELECT         Contact.ID
FROM           ContactSet
WHERE SET.ID = ?
//this is where I run into problems. I want to use the records returned from
//the previous SELECT query (expr1) but I'm unsure how. 
//Would it be expr1.ID or expr1.Set.ID?

Thank you.

A: 

this should work just fine or at least lead you to the final solution, you only need the one query:

declare @skillid int 
set @skillid = 1

SELECT C.*
  FROM  contact c
    inner join SetContact SC on (sc.contactId = C.contactId)
    inner join SkillSet SS on (ss.SetId = SC.SetId)
  WHERE (SS.SkillId = @SkillId)
Chris Lively
SELECT DISTINCT may be useful (depending on the data)
devio