0

I have a MySQL question, I'm wondering if the answers lies in using joins. I apologize in advance if the title is confusing or misleading.

I have 2 tables: Teams, Contractors

TEAMS
|team_id | location|
--------------------
|    1   |  space1 |
--------------------
|    2   |  space2 |
--------------------
|    3   |  space3 |
--------------------

CONTRACTORS
|cont_id | location| team_id|
-----------------------------
|    1   |  space1 |    1   |
-----------------------------
|    2   |  space1 |    0   |
-----------------------------
|    3   |  space3 |    3   |
-----------------------------
|    4   |  space3 |    3   |
-----------------------------
|    5   |  space3 |    0   |
-----------------------------

I would like to create a query that finds all the contractors that are at a specific location. The issue is, I only know the team_id. (team_id = 0 in the CONTRACTORS table means the contractor is not currently part of a team).

For example, I'm given the team_id = 3. The team with team_id = 3 is located at space3. I want to find all the contractors that are located at space3 (cont_id = 3, 4, 5 in this example).

Is there a way to achieve this with a single MySQL query? Or do I need to perform a query to get the location of the team, and then a 2nd query to find all contractors at that location?

1
  • Just a quick thank you to those who took a moment to help me out. :) Commented Jan 28, 2014 at 6:45

3 Answers 3

0
select location 
from CONTRACTORS 
inner join TEAMS on TEAMS.location = CONTRACTORS.location and TEAMS.team_id = 3
Sign up to request clarification or add additional context in comments.

1 Comment

I had to select CONTRACTORS.location, but otherwise this worked perfectly, thank you.
0

You can use join

SELECT        t.*,c.* 
FROM          TEAMS 
INNER JOIN    CONTRACTORS c 
ON            c.team_id = t.team_id 
WHERE         t.team_id = 3 

Comments

0

One SQL query:

SELECT cont_id
FROM teams, contractors
WHERE teams.location = contractors.location
AND teams.team_id = 3;

Replace '3' with the team you want.

Note: this query is only returning cont_id. You didn't specify what exactly you need, but I'm guessing at the very least you need the cont_id to identify the contractors.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.