YogeshChauhan . com

Learn how to use Self JOIN in SQL and MySQL

in SQL/MySQL on September 24, 2019

Self JOIN in SQL

SQL SELF JOIN works the same way as the JOIN keyword itself. The only difference is that SELF JOIN joins the columns form a table itself.

Take a look at the syntax:


SELECT columns
FROM table Aliases_1, table Aliases_2 WHERE condition;

 So as we can in the syntax above, the columns are from the same tables and we just join it to get desired results. We can use Aliases to give the columns different names in the result set.

Let’s take a look at the example.


SELECT b.CustomerName AS [Customer Name], b.ContactName AS [Contact Name]
FROM customers a, customers b 
WHERE a.ContactName=b.ContactName 
  and a.CustomerName='Janis D. Triplett';

That is an example for SQL.

NOTE: Square brackets are used in the aliases’ names as they contain spaces.

Now take a look at the example for MySQL. There is just slight difference. If you’re using phpmyadmin then you need to use the following example.


SELECT b.CustomerName, b.ContactName 
FROM customers AS a, 
      customers AS b 
WHERE a.ContactName=b.ContactName 
  and a.CustomerName='Janis D. Triplett';

We used aliases in the column names in SQL and in MySQL, we are using it for tables names. 

Both of the above example will give same results and they will find customer’s name and related contact person for that customer. 

amazon

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

How to Clone Objects in PHP?MiscHow to create a for loop in SCSS (Sass)?SCSS6 Different Functions to Sort Arrays in PHPPHPThe order Property in Flex Items in CSSCSSsubstring() Method in JavaScriptJavaScriptHow JavaScript classes allows us to do less typing (syntactic sugar)?JavaScript