MySql - INNER JOIN

MySQL INNER JOIN - Joining Related Data From Two or More Tables

MySQL INNER JOIN - Joining Related Data From Two or More Tables

Introduction

In relational databases like MySQL, data is often normalized and stored across multiple tables to avoid redundancy and improve data integrity. When querying this distributed data, it is often necessary to combine rows from two or more tables based on a related column between them. This operation is commonly known as a JOIN.

MySQL provides several types of joins, with INNER JOIN being one of the most commonly used. This guide provides an in-depth explanation of the INNER JOIN operation in MySQL, complete with syntax, use cases, examples, and best practices.

What is INNER JOIN?

The INNER JOIN keyword in MySQL is used to select records that have matching values in both tables involved in the join. It returns only the rows where there is a match between the specified columns of the participating tables.

Why Use INNER JOIN?

  • To combine data from multiple tables.
  • To retrieve meaningful relationships across tables.
  • To enhance the richness of the query output by merging relevant information.
  • To enforce logical connections between datasets.

INNER JOIN Syntax

SELECT columns
FROM table1
INNER JOIN table2
ON table1.common_column = table2.common_column;

Explanation

  • SELECT columns: Specifies the columns to be retrieved.
  • FROM table1: The first table in the join.
  • INNER JOIN table2: The second table to be joined with the first table.
  • ON table1.common_column = table2.common_column: The condition that defines how the tables are related.

Example Tables

Let’s consider two tables:

Customers Table

+----+----------+-----------+
| ID | Name     | City      |
+----+----------+-----------+
| 1  | John     | New York  |
| 2  | Jane     | London    |
| 3  | Michael  | Paris     |
| 4  | Sophia   | Berlin    |
+----+----------+-----------+

Orders Table

+----+------------+----------+
| ID | CustomerID | Product  |
+----+------------+----------+
| 1  | 1          | Laptop   |
| 2  | 3          | Phone    |
| 3  | 4          | Tablet   |
| 4  | 2          | Monitor  |
| 5  | 2          | Mouse    |
+----+------------+----------+

Basic INNER JOIN Example

SELECT Customers.Name, Orders.Product
FROM Customers
INNER JOIN Orders
ON Customers.ID = Orders.CustomerID;

Output

+----------+----------+
| Name     | Product  |
+----------+----------+
| John     | Laptop   |
| Jane     | Monitor  |
| Jane     | Mouse    |
| Michael  | Phone    |
| Sophia   | Tablet   |
+----------+----------+

This output shows only the customers who have placed orders, excluding customers who do not have corresponding records in the Orders table.

INNER JOIN with Multiple Conditions

Sometimes, you may need to join tables using multiple conditions.

SELECT Customers.Name, Customers.City, Orders.Product
FROM Customers
INNER JOIN Orders
ON Customers.ID = Orders.CustomerID
AND Customers.City = 'London';

Output

+------+--------+---------+
| Name | City   | Product |
+------+--------+---------+
| Jane | London | Monitor |
| Jane | London | Mouse   |
+------+--------+---------+

Using Table Aliases in INNER JOIN

Aliases make queries shorter and easier to read, especially with multiple joins.

SELECT C.Name, O.Product
FROM Customers AS C
INNER JOIN Orders AS O
ON C.ID = O.CustomerID;

INNER JOIN with WHERE Clause

We can further filter INNER JOIN results using the WHERE clause.

SELECT C.Name, O.Product
FROM Customers AS C
INNER JOIN Orders AS O
ON C.ID = O.CustomerID
WHERE O.Product = 'Laptop';

Output

+------+---------+
| Name | Product |
+------+---------+
| John | Laptop  |
+------+---------+

Joining More Than Two Tables

MySQL allows joining multiple tables with INNER JOIN. Let's introduce another table:

Products Table

+----+------------+---------+
| ID | Product    | Price   |
+----+------------+---------+
| 1  | Laptop     | 1000    |
| 2  | Phone      | 500     |
| 3  | Tablet     | 300     |
| 4  | Monitor    | 200     |
| 5  | Mouse      | 50      |
+----+------------+---------+

Query to Join Three Tables

SELECT C.Name, O.Product, P.Price
FROM Customers C
INNER JOIN Orders O ON C.ID = O.CustomerID
INNER JOIN Products P ON O.Product = P.Product;

Output

+----------+----------+-------+
| Name     | Product  | Price |
+----------+----------+-------+
| John     | Laptop   | 1000  |
| Jane     | Monitor  | 200   |
| Jane     | Mouse    | 50    |
| Michael  | Phone    | 500   |
| Sophia   | Tablet   | 300   |
+----------+----------+-------+



logo

MySQL

Beginner 5 Hours
MySQL INNER JOIN - Joining Related Data From Two or More Tables

MySQL INNER JOIN - Joining Related Data From Two or More Tables

Introduction

In relational databases like MySQL, data is often normalized and stored across multiple tables to avoid redundancy and improve data integrity. When querying this distributed data, it is often necessary to combine rows from two or more tables based on a related column between them. This operation is commonly known as a JOIN.

MySQL provides several types of joins, with INNER JOIN being one of the most commonly used. This guide provides an in-depth explanation of the INNER JOIN operation in MySQL, complete with syntax, use cases, examples, and best practices.

What is INNER JOIN?

The INNER JOIN keyword in MySQL is used to select records that have matching values in both tables involved in the join. It returns only the rows where there is a match between the specified columns of the participating tables.

Why Use INNER JOIN?

  • To combine data from multiple tables.
  • To retrieve meaningful relationships across tables.
  • To enhance the richness of the query output by merging relevant information.
  • To enforce logical connections between datasets.

INNER JOIN Syntax

SELECT columns FROM table1 INNER JOIN table2 ON table1.common_column = table2.common_column;

Explanation

  • SELECT columns: Specifies the columns to be retrieved.
  • FROM table1: The first table in the join.
  • INNER JOIN table2: The second table to be joined with the first table.
  • ON table1.common_column = table2.common_column: The condition that defines how the tables are related.

Example Tables

Let’s consider two tables:

Customers Table

+----+----------+-----------+ | ID | Name | City | +----+----------+-----------+ | 1 | John | New York | | 2 | Jane | London | | 3 | Michael | Paris | | 4 | Sophia | Berlin | +----+----------+-----------+

Orders Table

+----+------------+----------+ | ID | CustomerID | Product | +----+------------+----------+ | 1 | 1 | Laptop | | 2 | 3 | Phone | | 3 | 4 | Tablet | | 4 | 2 | Monitor | | 5 | 2 | Mouse | +----+------------+----------+

Basic INNER JOIN Example

SELECT Customers.Name, Orders.Product FROM Customers INNER JOIN Orders ON Customers.ID = Orders.CustomerID;

Output

+----------+----------+ | Name | Product | +----------+----------+ | John | Laptop | | Jane | Monitor | | Jane | Mouse | | Michael | Phone | | Sophia | Tablet | +----------+----------+

This output shows only the customers who have placed orders, excluding customers who do not have corresponding records in the Orders table.

INNER JOIN with Multiple Conditions

Sometimes, you may need to join tables using multiple conditions.

SELECT Customers.Name, Customers.City, Orders.Product FROM Customers INNER JOIN Orders ON Customers.ID = Orders.CustomerID AND Customers.City = 'London';

Output

+------+--------+---------+ | Name | City | Product | +------+--------+---------+ | Jane | London | Monitor | | Jane | London | Mouse | +------+--------+---------+

Using Table Aliases in INNER JOIN

Aliases make queries shorter and easier to read, especially with multiple joins.

SELECT C.Name, O.Product FROM Customers AS C INNER JOIN Orders AS O ON C.ID = O.CustomerID;

INNER JOIN with WHERE Clause

We can further filter INNER JOIN results using the WHERE clause.

SELECT C.Name, O.Product FROM Customers AS C INNER JOIN Orders AS O ON C.ID = O.CustomerID WHERE O.Product = 'Laptop';

Output

+------+---------+ | Name | Product | +------+---------+ | John | Laptop | +------+---------+

Joining More Than Two Tables

MySQL allows joining multiple tables with INNER JOIN. Let's introduce another table:

Products Table

+----+------------+---------+ | ID | Product | Price | +----+------------+---------+ | 1 | Laptop | 1000 | | 2 | Phone | 500 | | 3 | Tablet | 300 | | 4 | Monitor | 200 | | 5 | Mouse | 50 | +----+------------+---------+

Query to Join Three Tables

SELECT C.Name, O.Product, P.Price FROM Customers C INNER JOIN Orders O ON C.ID = O.CustomerID INNER JOIN Products P ON O.Product = P.Product;

Output

+----------+----------+-------+ | Name | Product | Price | +----------+----------+-------+ | John | Laptop | 1000 | | Jane | Monitor | 200 | | Jane | Mouse | 50 | | Michael | Phone | 500 | | Sophia | Tablet | 300 | +----------+----------+-------+



Related Tutorials

Frequently Asked Questions for MySQL

Use the command: CREATE INDEX index_name ON table_name (column_name); to create an index on a MySQL table.

To install MySQL on Windows, download the installer from the official MySQL website, run the setup, and follow the installation wizard to configure the server and set up user accounts.

MySQL is an open-source relational database management system (RDBMS) that uses SQL (Structured Query Language) for managing and manipulating databases. It is widely used in web applications for its speed and reliability.

Use the command: INSERT INTO table_name (column1, column2) VALUES (value1, value2); to add records to a MySQL table.

Use the command: mysql -u username -p database_name < data.sql; to import data from a SQL file into a MySQL database.

DELETE removes records based on a condition and can be rolled back, while TRUNCATE removes all records from a table and cannot be rolled back.

A trigger is a set of SQL statements that automatically execute in response to certain events on a MySQL table, such as INSERT, UPDATE, or DELETE.

The default MySQL port is 3306, and the root password is set during installation. If not set, you may need to configure it manually.

Replication in MySQL allows data from one MySQL server (master) to be copied to one or more servers (slaves), providing data redundancy and load balancing.

 A primary key is a unique identifier for a record in a MySQL table, ensuring that no two records have the same key value.

 Use the command: SELECT column1, column2 FROM table_name; to fetch data from a MySQL table.

 Use the command: CREATE DATABASE database_name; to create a new MySQL database.

Use the command: CREATE PROCEDURE procedure_name() BEGIN SQL_statements; END; to define a stored procedure in MySQL.

Indexing in MySQL improves query performance by allowing the database to find rows more quickly. Common index types include PRIMARY KEY, UNIQUE, and FULLTEXT.

Use the command: UPDATE table_name SET column1 = value1 WHERE condition; to modify existing records in a MySQL table.

CHAR is a fixed-length string data type, while VARCHAR is variable-length. CHAR is faster for fixed-size data, whereas VARCHAR saves space for variable-length data.

MyISAM is a storage engine that offers fast read operations but lacks support for transactions, while InnoDB supports transactions and foreign keys, providing better data integrity.

A stored procedure is a set of SQL statements that can be stored and executed on the MySQL server, allowing for modular programming and code reuse.

Use the command: mysqldump -u username -p database_name > backup.sql; to create a backup of a MySQL database.

Use the command: DELETE FROM table_name WHERE condition; to remove records from a MySQL table.

A foreign key is a column or set of columns in one MySQL table that references the primary key in another, establishing a relationship between the two tables.

Use the command: CREATE TRIGGER trigger_name BEFORE INSERT ON table_name FOR EACH ROW BEGIN SQL_statements; END; to create a trigger in MySQL.

Normalization in MySQL is the process of organizing data to reduce redundancy and improve data integrity by dividing large tables into smaller ones.

JOIN is used to combine rows from two or more MySQL tables based on a related column, allowing for complex queries and data retrieval.

Use the command: mysqldump -u username -p database_name > backup.sql; to export a MySQL database to a SQL file.

line

Copyrights © 2024 letsupdateskills All rights reserved