D
D
Dmitry Morozov2018-05-12 17:24:01
MySQL
Dmitry Morozov, 2018-05-12 17:24:01

JOIN MySQL with 2 tables?

Good day, I ran into the following problem:
There is a request:

SELECT to_t.name, to_t.id  FROM to_team_games to_t_g LEFT JOIN to_teams to_t on to_t_g.team_id_1 = to_t.id WHERE to_t_g = 1

The task is such that you need to connect 2 columns (team_id_1, team_id_2) of the to_team_games table with to_teams and get the necessary columns from there, namely name, id. In the query above, I will only get data for 1 column team_id_1, but is it possible to get the same fields in 2 columns team_id_2 in one query?
Something like:
SELECT to_t.name, to_t.id  FROM to_team_games to_t_g LEFT JOIN to_teams to_t on to_t_g.team_id_1 = to_t.id LEFT JOIN to_teams to_t on to_t_g.team_id_2 = to_t.id WHERE to_t_g = 1

But then this request will not work ((

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Ruslan., 2018-05-12
@index1

Here you need to set a unique alias for the third table, then it will work.
For example like this:

SELECT to_t.name,  to_t.id, to_t2.name,  to_t2.id
   FROM to_team_games to_t_g 
     LEFT JOIN to_teams to_t   on to_t_g.team_id_1 = to_t.id 
     LEFT JOIN to_teams to_t2 on to_t_g.team_id_2 = to_t2.id 
WHERE to_t_g.id= 1

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question