Table matches
has the following columns:
id, teamA, teamB
Table teams
contains:
id, name
I want to output both of the teams, and managed to do it with this:
$sql1 = SELECT teams.name FROM matches LEFT JOIN teams ON matches.teamA = teams.id
$sql2 = SELECT teams.name FROM matches LEFT JOIN teams ON matches.teamb = teams.id
Then I output it with a while loop:
echo $sql1->name, $sql2->name
The problem I had when trying one query was, that the team name could only be output once per row.
How would this work with one query?
SELECT team1.name as team1name, // Select the first team name from the table aliased as team1, aliasing that column as team1
team2.name as team2name // Select the second team name from the table aliased as team2, aliasing that column as team2
FROM matches
LEFT JOIN teams team1 // Alias our first join to teams on teamA as team1
ON matches.teamA = team1.id
LEFT JOIN teams team2 // Alias our second join to teams on teamB as team2
ON matches.teamB = teams2.id
When you execute this query, you should get 2 team names returned, one aliased as team1name
, the other as team2name
; so when you retrieve these to your PHP, they will have those aliased column names
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments