dotminic
dotminic

Reputation: 1145

MySQL join two tables and retun data from both tables

I have a pretty simple MySQL query, that joins two tables:

SELECT teams.id, teams.name, players.id, players.name, players.teamId
FROM teams
LEFT JOIN players
ON teams.id = players.zoneId
WHERE teamId = 3

When I then fetch the rows, I can use the data like this:

echo($row["name"] . ", " . $row["id"]);

The data contained in the array, is the data from the players table. How can I also access the data from the "teams" table ?

Thanks.

Upvotes: 1

Views: 111

Answers (1)

dcp
dcp

Reputation: 55449

Use aliases for column names to differentiate between columns from team table and players table that have same names.

SELECT teams.id as team_id, teams.name as team_name, players.id, players.name, players.teamId
FROM teams
LEFT JOIN players
ON teams.id = players.zoneId
WHERE teamId = 3

Then you can use the below to get team name and team id:

$row["team_name"]
$row["team_id"]

If it were me, I'd also use aliases for the player fields (e.g. player_id, etc.) just to make the code as clear as possible. Clear code == better maintainability.

Upvotes: 6

Related Questions