Skip to content
Advertisement

How can I merge my 3 queries into one query that returns all

The first query gets the date of a football match for the given week, the second query gets the name of the home team for each match of the week and the third query the away team. How can I structure the query so that it produces one table of results instead of 3

SELECT fixtures.matchDate
FROM weeks 
INNER JOIN fixtures ON weeks.weekID = fixtures.weekID
WHERE (fixtures.weekID = 1)

SELECT teams.teamName AS homeTeam
FROM fixtures 
INNER JOIN teams ON fixtures.homeTeam = teams.teamID
WHERE (fixtures.weekID = 1)

SELECT teams.teamName AS awayTeam
FROM fixtures
INNER JOIN teams ON fixtures.awayTeam = teams.teamID
WHERE  (fixtures.weekID = 1)

Advertisement

Answer

It depends, how exactly do you want the results to look? Maybe this will work:

SELECT 
  fix.matchDate AS matchDate,
  ht.teamName AS homeTeam,
  at.teamName AS awayTeam
FROM 
  fixtures fix
  INNER JOIN teams ht ON fix.homeTeam = ht.teamID
  INNER JOIN teams at ON fix.awayTeam = at.teamID
WHERE 
  fixtures.weekID = 1

N.B. It’s not clear that you need the join to weeks at all, because you’re not selecting anything from it, and the WHERE clause already restricts to the specific week. It would only be useful as a failsafe to ensure the week selected is valid in the list of weeks.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement