简体   繁体   中英

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.

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 (eg player_id, etc.) just to make the code as clear as possible. Clear code == better maintainability.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM