Search code examples
phpsqlslim

Cannot extract data with multiple LEFT JOIN


I need to extract all the countries which are matches that play into a specific date, the table structure is this:

TABLE NAME  |  FIELDS
country     | id, name  
round       | id, season_id
season      | id, competition_id
competition | id, country_id
match       | id, round_id, date

a single match record have the following composition:

id: 60856
round_id: 65
date: 2018-06-02 00:00:00

as you can see I've the round_id where the match is disputed. On the round table there is the following design:

id: 65
season_id: 280

the season represent the container of the round, so a season record have this structure:

id: 161
competition_id: 48

and a season have a competition that contains all the rounds. A competition record contains the country:

id: 48
coutry_id: 2

and finally the country:

id: 2
name: albania

How can I extract all the countries that have matches which playing today?

This is what I tried:

$app->get('/country/get_countries/{date}', function (Request $request, Response $response, array $args)
{
    $sql = $this->db->query("SELECT * FROM country
      LEFT JOIN `match` ON round_id = round.id
      LEFT JOIN round ON season_id = season.id
      LEFT JOIN season ON competition_id = competition.id
      WHERE match.datetime = " . $args["date"] . "");

    $sql->execute();
    $countries = $sql->fetchAll();
    return $response->withJson($countries);
});

this will return:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'round.id' in 'on clause'

UPDATE:

  $sql = $this->db->query("SELECT * FROM country
  LEFT JOIN competition ON country_id = competition.country_id
  LEFT JOIN competition_seasons ON competition_id = competition.id
  LEFT JOIN competition_rounds ON competition_rounds.season_id = competition_seasons.id
  LEFT JOIN `match` ON match.round_id = competition_rounds.id
  WHERE match.datetime = " . $args["date"] . "");

Solution

  • SELECT * FROM country
          LEFT JOIN competition ON country.id = competition.country_id
          LEFT JOIN season ON season.competition_id= competition.id
          LEFT JOIN round ON round.season_id= season.id
          LEFT JOIN match ON match.round_id= round.id
          WHERE match.datetime = " . $args["date"] . ""