Sooner or later we will need to join two or more tables in our database. Joins are necessary as tables are usually constructed to each store a specific type of data only to improve efficiency.
As an example, we could have an "employee" table that stores the names of employees only, and then a "details" table that stores other details of the employee. The tables would be linked using perhaps an employee ID number.
To try to store all the data in one table would essentially make the table too wide and it would be slower and less efficient to process. The tutorial below will show you how to make the best use of joining tables in MySQL.
Suppose our "employees" table looks like:
id | first_name | last_name |
---|---|---|
1 | Paul | Pitterson |
2 | Francine | Beecham |
3 | Raul | DiNozzo |
4 | Anthony | DiNozzo |
And our "details" table looks like:
id | age |
---|---|
1 | 24 |
2 | 52 |
3 | 28 |
4 | 33 |
If we wanted to view the names and ages of employees at the same time we would have to join the tables using the ID number field.
To achieve the effect of a join on the tables shown above, we can use the following SQL:
SELECT employees.*, details.age FROM employees, details WHERE employees.id = details.id;
What this code does is select the appropriate fields from both tables and then uses the WHERE clause and the condition "employees.id = details.id" to perform the implicit join.
The result of the query would be:
id | first_name | last_name | age |
---|---|---|---|
1 | Paul | Pitterson | 24 |
2 | Francine | Beecham | 52 |
3 | Raul | DiNozzo | 28 |
4 | Anthony | DiNozzo | 33 |
And voila, we have performed our join. We hope this tutorial was useful.