Joins means combining data from two or more tables, based on a related column. A table join creates a temporary table showing the data from the joined tables.
For example, we have two tables that follow, the table named tblcustomers stores the information about the customer
idNameAddressRegDate1John DoeNew Delhi2024-01-022Anuj kumarNoida UP2024-04-013Amit SinghBangalore Karnataka2024-05-014AlexChennai Tamilnadu2024-06-09
The tbloders table store the information about the individual orders with their corresponding amount:
idCustomer_IdProduct_NameAmount11iPhone92000022Sony TV4562332Laptop8564143Book45654Toys1452
Rather than storing the customer name in both tables, the tblorders table contains a reference to the customer id that appears in tblcustomers table. We will use join to select the corresponding data from both tables.
Syntax:
SELECT <ColumnName1>,<ColumnName2>,<ColumnNameN>
From <TableName1>
Join <TableName2> on <TableName1.ColumnName1>=<TableName2.ColumnName2>
Where <Condition>
Order By <ColumnName1>,<ColumnName2>,<ColumnNameN>;
In the Above Syntax:
ColumnName1 in TableName1 is usually that table’s Primary key.
ColumnName2 in TableName2 is a Foreign Key in that table.
ColumnName1 and ColumnName2 must have the same Data Type and for certain data types, the same size.
Example using the above two tables tblcustomers and tblorders
SELECT tblcustomers.id, tblcustomers.Name, tblcustomers.Address, tblorders.Product_Name, tblorders.Amount
FROM tblcustomers
join tblorders on tblorders.Customer_id=tblcustomers.id
ORDER BY tblcustomers.id;
Output Will be:
idNameAddressProduct_NameAmount1John DoeNew DelhiiPhone9200002Anuj kumarNoida UPSony TV456232Anuj kumarNoida UPLaptop856413Amit SinghBangalore KarnatakaBook4564AlexChennai TamilnaduToys1452
The post SQL Joins appeared first on PHPGurukul.
Source: Read MoreÂ