INNER JOIN is the simplest JOIN type and if you want to understand the clue of using JOINS,
you definitely should start from this point.
In this article i will show you how to use INNER JOIN and explain when to use it properly.
INNER JOIN allows us to combine multiple tables together.
Let's say, we have two tables.
users table
id | first_name | last_name | customer_id |
1 | John | Doe | 11 |
2 | Adam | Novak | 12 |
3 | Robert | Grenn | 13 |
4 | Adam | Morrick | 14 |
customers table
id | active | saldo | premium |
11 | 1 | 100 | 0 |
12 | 0 | 0 | 0 |
13 | 1 | 150 | 1 |
15 | 1 | 100 | 0 |
We have customer_id column in users table which is responding to the id column inside customers table.
With INNER JOIN we can combine both tables and show only results which has corresponding customer_id and id in those tables.
The correct syntax for INNER JOIN in this situation should show us result like this:
id | first_name | last_name | customer_id | id | active | saldo | premium |
1 | John | Doe | 11 | 11 | 1 | 100 | 0 |
2 | Adam | Novak | 12 | 12 | 0 | 0 | 0 |
3 | Robert | Grenn | 13 | 13 | 1 | 150 | 1 |
As you can see, INNER JOIN combined only records which matches successfuly customer_id with id from customers table.
The correct query for this operation should look like this:
SELECT * FROM users INNER JOIN customers ON users.customer_id = customers.id
Worth to remember is that INNER JOIN does not care about tables order. It works in both ways.
Now when you know how to use INNER JOIN on whole tables, you can just get the data you want. Let's say, you want to get the saldo from
users which have a customer record.
The code below will help you with this:
SELECT users.id, first_name, last_name, saldo FROM users INNER JOIN customers ON users.customer_id = customers.id
The query above will result in result like this:
id | first_name | last_name | saldo |
1 | John | Doe | 100 |
2 | Adam | Novak | 0 |
3 | Robert | Grenn | 150 |