Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - JOIN 2 tables with 2 ID's in common

Tags:

join

mysql

I have 2 tables that I need to get information from, and would like to get the information in one single query.

The situation is this :

table "matches" :

id
team_A_id
team_B_id

table "teams" :

id
name

The objective is to retrieve information from table "matches" (football matches) and join the information with the table "teams". I need this because my webservice provider doesn't have the xml data in my language (portuguese), and so I need to offer my client the option to translate certain team names to portuguese, otherwise I'd add the team names directly on the "matches" table. The problem is that I need to JOIN the 2 tables with 2 id's. I know how to join tables with 1 id in common, but can't figure out how to do it with 2 id's, and mantaining the information from the 2 teams involved in each match intact.

Is this possible? Or do I have to create separate queries?

like image 990
yoda Avatar asked Dec 17 '09 12:12

yoda


People also ask

How do I join two tables in common field in SQL?

The join is done by the JOIN operator. In the FROM clause, the name of the first table ( product ) is followed by a JOIN keyword then by the name of the second table ( category ). This is then followed by the keyword ON and by the condition for joining the rows from the different tables.

What is the most efficient way of joining 2 table in same database?

Method 1: Relational Algebra Relational algebra is the most common way of writing a query and also the most natural way to do so. The code is clean, easy to troubleshoot, and unsurprisingly, it is also the most efficient way to join two tables.

What clause is used to join two 2 tables together in a MySQL command?

A JOIN clause is used to combine rows from two or more tables, based on a related column between them.

Can we apply JOINs on 2 tables which has no related data?

Yes, you can! The longer answer is yes, there are a few ways to combine two tables without a common column, including CROSS JOIN (Cartesian product) and UNION. The latter is technically not a join but can be handy for merging tables in SQL.


2 Answers

select match.*, teama.name, teamb.name
from matches as match
inner join teams as teama on teama.id = match.team_A_id
inner join teams as teamb on teamb.id = match.team_B_id

would work in SQL Server and presumably MySQL too.

like image 83
Rich Avatar answered Sep 27 '22 22:09

Rich


Include the teams table a second time (with a different alias) and treat the query as being between three tables:

SELECT *
FROM matches m
JOIN teams t1 ON m.team_A_id = t1.id
JOIN teams t2 ON m.team_B_id = t2.id
like image 28
cletus Avatar answered Sep 27 '22 21:09

cletus