Joins

Joins are used along with SELECT statement when ever there is a need to retrieve data from multiple tables.

Commonly used Joins in MySQL are as follows:

  1. INNER JOIN
  2. LEFT JOIN
  3. RIGHT JOIN
  4. CROSS JOIN

Let us consider the below tables for our understanding:

TABLE1:

AZ
a1
b4
d5

TABLE2:

AX
a10
e17
d30

1. INNER JOIN

INNER JOIN combines the values from both the tables based on matching criteria.

Below is a basic example of how inner join works:

SELECT * FROM TABLE1 INNER JOIN TABLE2 where TABLE1.A=TABLE2.A;

Result:

AZAX
a1a10
d5d30

2. LEFT JOIN

LEFT JOIN returns all the values from the Left hand table of the condition and returns only the matching values from the second table. The unmatched row values of right hand table will be represented as NULL.

SELECT * FROM TABLE1 LEFT JOIN TABLE2 ON TABLE1.A=TABLE2.A;

Result:

AZAX
a1a10
d5d30
b4nullnull

3. RIGHT JOIN

RIGHT JOIN returns all the values from the right hand table of the condition and returns only the matching values from the left hand table. The unmatched row values of left hand table will be represented as NULL.

SELECT * FROM TABLE1 RIGHT JOIN TABLE2 ON TABLE1.A=TABLE2.A;

Result:

AZAX
a1a10
d5d30
nullnulle17

4. CROSS JOIN

CROSS JOIN matches each row of the first table with every row of the second table.

SELECT A,Z,X from TABLE1 CROSS JOIN TABLE2;

Result:

AZX
a110
a117
a130
b410
b417
b430
d510
d517
d530