Distances Table:
| StartTeam | DestinationTeam | Distances |
|---|---|---|
| Atlanta Hawks | Boston Celtics | 1234 |
| Brooklyn Nets | Atlanta Hawks | 212 |
Stadiums Table:
| TeamName | Enabled |
|---|---|
| Atlanta Hawks | 1 |
| Boston Celtics | 0 |
| Brooklyn Nets | 1 |
I need a sql query that will check if the StartTeam and DestinationTeam are both Enabled within the Stadiums table.
I tried this query to check if both teams are within the Stadiums table but it’s clearly not correct. Would love some help!
SELECT *
FROM Distances d
LEFT JOIN Stadiums s
ON d.StartTeam = s.[Team Name]
WHERE s.Enabled AND (
SELECT *
FROM Distances d
LEFT JOIN Stadiums s
ON d.DestinationTeam = s.[Team Name]
WHERE s.Enabled = 1
)
ORDER BY d.DestinationTeam ASC
So the working query would spit out the second row since both Brooklyn Nets and Atlanta Hawks are enabled. The first row wouldn’t be returned since Boston Celtics is not enabled.
DESIRED OUTPUT:
| StartTeam | DestinationTeam | Distances |
|---|---|---|
| Brooklyn Nets | Atlanta Hawks | 212 |
>Solution :
Join Distances to Stadiums twice:
SELECT d.*
FROM Distances d
INNER JOIN Stadiums s1 ON s1.TeamName = d.StartTeam
INNER JOIN Stadiums s2 ON s2.TeamName = d.DestinationTeam
WHERE s1.Enabled + s2.Enabled = 2;
Note that the criterion in the WHERE clause is asserting that both the start and destination teams are enabled.