是否可以编写这样一个通用查询?通用是指我不需要键入作为外键的列名,这样我就可以将此查询用于其他表。简单的例子:
[table workers]
ID [PK] | worker | department [FK]
--------+--------+-----------
1 | Smith | 2
[table departments]
ID [PK] | department
--------+------------+
1 | Paris |
2 | Oslo |
查询后SELECT/JOIN
会显示为:
ID [PK] | worker | department [FK]
--------+--------+-----------
1 | Smith | Oslo
但不是写:
SELECT workers.ID, workers.worker, departments.department
FROM workers JOIN departments ON workers.department = departments.ID;
这仅适用于workers
并且departments
我更喜欢更通用的东西,例如:
SELECT * FROM [tableName] JOIN [referenced table#1],
[referenced table#2]...[#n]
ON [tableName].FK#1 = [referenced table#1].[2nd column],
[tableName].FK#2 = [referenced table#2].[2nd column]...#n
where #n
- 外键及其引用表的数量,每个表都不同。