This tip explains how to create SQL joins in a very simple way. With this, developers need not put much effort to frame SQL Joins. This is very simple and easy to do.
Note: Please feel free to send comments... thanks in advance.
The idea behind posting this tip is to provide users with a simple way of creating
join queries. Most people might already know it. But still it might help newbies.
Using the Code
For this explanation, I have created two tables as follows:
Table 1. T_EMPLOYEE (T stands for table, this is the method that I use to create tables)
Below is my
Employee table design:
Table 2. T_DEPARTMENTS
Below is my
Department table design:
And please make sure that you have some rows(data) in both the tables.
Note: Relationship between fields has already been created between
Now moving into the actual stuff about creating
Joins, please follow the steps given below:
- Open SQL Server 2008 Management Studio
- Expand your database, locate "Views" and right click on that
- Click on "New View"
- The following dialog will be displayed:
- Select both the tables and click on Add button... and Close the window.. you will find the following screen with the relationship between both the tables which we made.
- Observe that it has pre-populated basic
INNER JOIN query based on
Foreign Key relation.
- Now for our convenience and requirement, we don't require all the fields. So
Select the required fields from both the tables.
- I have selected the following fields. And for ease of understanding, I have given alias names too.
- That's it. Now you have your SQL query which joins two tables. Execute it, then you will find the following table as an output table.
- So, you can use this for:
- Joining more than two tables
- Union of tables
- and lot more
Points of Interest
This is so simple and pretty straight forward.