SQL- 查询具有引用其他外键字段的外键字段的 table

SQL-Query for a table with a foreign-key-field that references other foreign-key-fields

我的数据库中有以下 table 的结构:

[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       |

table "workers" 有一个外键字段 ("combined")。 table "combined" 有一个字段名和一个外键字段 "helper",它又是一个带有两个外键字段的 table。

我现在的问题是,什么是最简单的SQL-查询得到以下table:

[table workers]
ID [PK] | worker | combined-Name| department | location
--------+--------+--------------+------------+-----------
1       | John   |    name2     | Development|   Paris
--------------------------------+------------+-----------
2       | Adam   |    name1     | Production |   Berlin

我已经用一些 LEFT-JOINS 尝试过,但没能成功地将所有 "clearnames" 连接到 table "workers"

此查询有效:

SELECT w.ID, worker, c.name AS `combined-Name`, d.department, l.department as 
location FROM workers w
LEFT JOIN combined c ON c.ID = w.combined
LEFT JOIN helper h ON h.ID = c.helper
LEFT JOIN departments d ON d.ID = h.department
LEFT JOIN location l ON l.ID = h.location
GROUP BY w.ID

我使用 AS 关键字将名称设置为您的首选输出。

这是使用提供的结构和数据在本地测试的。

它基本上是 4 个简单的左连接,然后 select 不是 select 外部表的名称列而是 ID 的 select。

引用c.name上的别名是因为我们需要转义特殊字符-

使用以下查询:

select [workers].worker,[combined].name as combined-name,[departments].name as department,[location].name as location  from [workers]
left join [combined] on [workers].combined = [combined].combined
left join [helper] on [helper].ID = [combined].helper
left join [departments] on [departments].ID = [helper].department
left join [location] on [location].ID = [helper].location