Home » SQL

SQL query to join two tables



In this article, we are going to learn about SQL joins and going to join two tables with it, to get the whole data from both tables.
Submitted by Manu Jemini, on March 11, 2018

Joining two tables is an operation every back-end developer should have access to. Because of the situations we face during development, the approach for getting the records must be simple.

Now the approach is that, make an alias of the table and use that alias to choose which fields you want to have. Advantages are numerous not to mention that you will not need to use left or right or inner or outer join in any way which definitely makes query complex.

Let’s understand the concept. The first thing we should decide the tables we will need to complete our query. Then, you should choose which field you want to have the result by using the alias. The third thing is you should give a condition in which the query should select result. For example, A.eid = B.eid.

This concept is particularly useful in the cases when you want to have a very tight grip on your result’s fields.

Below we have example clearly explaining the concepts we have gone through. We will use the unique keys in the first example. Keep a close eye on how we can easily choose the fields of the records while joining the tables.

Table (employee) having three fields and four data in it,

Id		Name		Address

100		Aman		Mumbai
200		Arun		Pune
300		Karan		Delhi
400		Aman		Mumbai

Table (users) having three fields and two data in it,

eid		cid		Name

100		100		Shubham
200		200		Abhishek

Now, we have two tables in our database having different fields rather than one which is eid and now we are going to join both the tables in two ways. The first query is to find whole data and second one is to select data with a condition in it.

Query 1:

SELECT E1.name, E2.name  
FROM employee E1 , users E2;

Output:

SQL query to join two tables 1

Query 2:

SELECT E1.name, E2.name 
FROM employee E1 , users E2 
WHERE E1.eid=E2.eid;

Output:

SQL query to join two tables 1






Was this page helpful? Please share with your friends...

Are you a blogger? Join our Blogging forum.



Comments and Discussions





© https://www.includehelp.com (2015-2018), Some rights reserved.




close Like other websites, this site uses cookies to deliver relevant ads based on your interest, by using our website, you acknowledge that you have read our privacy policy.