I have the following structure of tables in my database:
[table workers]
ID [PK] | worker | combined [FK]
--------+--------+--------------+
1 | John | 2
--------------------------------+
2 | Adam | 1
[table combined]
ID [PK] | name | helper [FK]
--------+----------------------+
1 | name1 | 1
2 | name2 | 2
[table helper]
ID [PK] | department [FK] | location [FK]
--------+-------------+-------------------
1 | 2 | 3
2 | 1 | 1
[table departments]
ID [PK] | department
--------+-------------+
1 | Development |
2 | Production |
[table location]
ID [PK] | department
--------+--------------+
1 | Paris |
2 | London |
3 | Berlin |
The table "workers" has an foreign-key-field ("combined"). The table "combined" has a field name and a foreign-key-field "helper" which again is a table with two foreign-key-fields.
My question is now, what is the simplest SQL-Query to get the following table:
[table workers]
ID [PK] | worker | combined-Name| department | location
--------+--------+--------------+------------+-----------
1 | John | name2 | Development| Paris
--------------------------------+------------+-----------
2 | Adam | name1 | Production | Berlin
I tried it already with some LEFT-JOINS but did not manage it to get all "clearnames" to the table "workers"
This query would work:
I used the
ASkeyword to set the names to your preferred output.This was tested locally using the provided structures and data.
It's basically 4 simple left joins, and then instead of selecting the ID's I select the name columns of the foreign tables.
The alias on
c.nameis quoted because we need to escape the special character-