mysql
  1. mysql-inner-join

Inner Join - (MySQL Join)

In MySQL, the INNER JOIN keyword is used to return only the matching rows from multiple tables. In this tutorial, we'll look at how to use INNER JOIN to combine data from two or more tables.

Syntax

Here's the basic syntax for using INNER JOIN in MySQL:

SELECT column1, column2, ...
FROM table1
INNER JOIN table2
ON table1.column = table2.column;

In the above syntax, "table1" and "table2" are the names of the tables you want to join, and "column1", "column2", etc. are the names of the columns you want to retrieve data from.

Example

Suppose we have two tables: "customers" and "orders". The "customers" table has the following columns: "customer_id", "name", and "email". The "orders" table has the following columns: "order_id", "customer_id", "order_date", and "total_price".

Here's an example of using INNER JOIN to combine data from the two tables:

SELECT customers.name, orders.order_date, orders.total_price
FROM customers
INNER JOIN orders
ON customers.customer_id = orders.customer_id;

This query will return the name of the customer, the date the order was placed, and the total price of the order.

Output

The output of the above query might look something like this:

| name      | order_date | total_price |
|-----------|------------|-------------|
| John Doe  | 2021-01-01 | 100.00      |
| Jane Smith| 2021-01-02 | 50.00       |
| John Doe  | 2021-01-03 | 75.00       |
| Bob Smith | 2021-01-04 | 200.00      |

Explanation

In the example above, we used INNER JOIN to combine data from the "customers" and "orders" tables. Specifically, we only returned rows where the "customer_id" column in the "customers" table matched the "customer_id" column in the "orders" table.

We then selected the "name" column from the "customers" table and the "order_date" and "total_price" columns from the "orders" table.

Use

INNER JOIN is useful for combining data from multiple tables when you only want to see rows that have matching data in both tables. This can be useful when you have related data in multiple tables and want to view it all at once.

Important Points

  • INNER JOIN is used to return only the matching rows from multiple tables.
  • You must specify the columns you want to select from each table.
  • You must specify the columns you want to join the tables on using the "ON" keyword.
  • INNER JOIN only returns rows where there is a match in both tables.

Summary

In this tutorial, we looked at using INNER JOIN to combine data from multiple tables in MySQL. We covered the syntax, example, output, explanation, use, and important points of INNER JOIN. With this knowledge, you can now use INNER JOIN to retrieve and combine information from multiple tables in your MySQL database.

Published on: