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:
And our "details" table looks like:
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:
And voila, we have performed our join. We hope this tutorial was useful.