I have two tables in a company database named employee
and branch
with a single foreign key each. The employee
table looks like this:
+------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+----------------+
| emp_id | int | NO | PRI | NULL | auto_increment |
| first_name | varchar(30) | YES | | NULL | |
| last_name | varchar(30) | YES | | NULL | |
| birth_date | date | YES | | NULL | |
| sex | varchar(1) | YES | | NULL | |
| salary | int | YES | | NULL | |
| super_id | int | YES | MUL | NULL | |
| branch_id | int | YES | MUL | NULL | |
+------------+-------------+------+-----+---------+----------------+
And the branch table looks like this:
+----------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------------+-------------+------+-----+---------+-------+
| branch_id | int | NO | PRI | NULL | |
| branch_name | varchar(30) | YES | | NULL | |
| mgr_id | int | YES | MUL | NULL | |
| mgr_start_date | date | YES | | NULL | |
+----------------+-------------+------+-----+---------+-------+
In the employee table, the branch_id
foreign key references the branch_id
of the branch
table. In the branch table, the manager_id
foreign key references the employee_id
of the employee
table.
I would form two joins between these two tables in circular fashion(saying informally) such that employee.branch_id
forms a join with branch.branch_id
, and such that branch.manager_id
forms a join with employee.employee_id
.
So what I want the query with these two joins to return is:
employee.first_name AS employee_name, employee.branch_id, branch.branch_name, branch.manager_id, employee.employee_id AS manager_name
I couldn't think of a possible solution to this issue as the LEFT table in each of the joins is different and I don't know how to define multiple LEFT tables for each join in a single SQL query.
DBMS: MySQL v8.0.26
P.S: My question is different from this question as in the aforementioned question, the LEFT table for both of the joins is the same and in my case, it is not.