MYSQL LEFT JOIN
The LEFT JOIN
will return all the records from the left table and the matched records from the right table.
Syntax for LEFT JOIN
SELECT column_name(s)
FROM table_name_1
LEFT JOIN table_name_2
ON table_name_1.column_name = table_name_2.column_name;
Assume the table employees
with the following data.
empno | name | age | department_id | location | salary | emp_type_id |
---|---|---|---|---|---|---|
1 | Andrew | 30 | 4 | India | 100000 | 2 |
2 | Beslin | 29 | 3 | India | 90000 | 1 |
3 | Joanna | 23 | 2 | USA | 500000 | 1 |
4 | Tianna | 22 | 4 | Canada | 500000 | 1 |
5 | Ani | 31 | 4 | USA | 700000 |
Then the `employeetype' with the following data
emp_type_id | emp_type |
---|---|
1 | Full-Time |
2 | Contract |
Example
select employees.name,employees.location,employeetype.emp_type from employees
left join employeetype
on employees.emp_type_id= employeetype.emp_type_id;
In the above example, the employee
table is the left table which will return all the records and the employeetype
is the right table which returns the matched records and unmatched records value will be null
.
Output
name | location | emp_type |
---|---|---|
Andrew | India | Contract |
Beslin | India | Full-Time |
Joanna | USA | Full-Time |
Tianna | Canada | Full-Time |
Ani | USA |