Categories: Development

The MySQL Inner join

A MySQL Join is when data is collected from two or more tables and “joined” on keys to return as one, saving you doing multiple queries.

There are several types of joins, inner is the most common and it is summed up with this diagram

inner join mysql

Inner join is from two tables where a key from table1 = key from table2, returning selected values from both tables.

SELECT table1.col, table1.col, table2.col, table2.col
FROM table1
INNER JOIN table2 ON table1.user_id = table2.user_id;

You can return as many or little (atleast 1 obviously) from either tables.

Example

For this post a small example database has been setup, Consisting of a users and login_data table. The users table has user_id, username, email, posts and score. login_data has user_id, result and when.

I want to get the login_data values for users whilst also returning their username. The login_data table does not store the username just the user_id making it a perfect scenario to do an inner join.

I can pair the user_id values from users and login_data

SELECT users.user_id, users.username, login_data.when, login_data.result
FROM users
INNER JOIN login_data ON users.user_id = login_data.user_id

Returns

user_id username when result
264 Johnny 2019-06-09 17:21:03 1
264 Johnny 2019-06-10 11:44:03 1
208 Sam 2019-06-18 10:11:03 1
201 Andy 2019-06-14 06:28:03 1
264 Johnny 2019-06-17 12:31:03 1

Had i need to only view the login data fro a certain user i can filter with a WHERE on their user_id like:

SELECT users.user_id, users.username, login_data.when, login_data.result
FROM users
INNER JOIN login_data ON users.user_id = login_data.user_id WHERE users.user_id = '264';

For further reading here is the official docs.

Share
Tags: How toMYSQL

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago