MySQL SQL

MySQL Self Join

MySQL Self Join

A self join is just a normal join except that it joins the table to itself.

Self Join Syntax

				
					SELECT column_name(s)
FROM table1 T1, table1 T2
WHERE condition;
				
			

Two distinct table aliases for the same table are T1 and T2.

Demo Database

We’ll be using the well-known Northwind sample database in this tutorial.

A sample from the “Customers” table is shown below:

CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
1

Alfreds FutterkisteMaria AndersObere Str. 57Berlin12209Germany
2Ana Trujillo Emparedados y heladosAna TrujilloAvda. de la Constitución 2222México D.F.05021Mexico
3Antonio Moreno TaqueríaAntonio MorenoMataderos 2312México D.F.05023Mexico

MySQL Self Join Example

Customers from the same city are matched using the SQL statement that follows:

Example

				
					SELECT A.CustomerName AS CustomerName1, B.CustomerName AS CustomerName2, A.City
FROM Customers A, Customers B
WHERE A.CustomerID <> B.CustomerID
AND A.City = B.City
ORDER BY A.City;
				
			
Share this Doc

MySQL Self Join

Or copy link

Explore Topic