SQL Access:两个表之间的多个内部联接

时间:2017-01-31 10:41:32

标签: sql ms-access inner-join

我在Microsoft Access中工作。

我有两个表,生产和试剂。

Reagents
- Reagent Reference ID (text)
- Supplier (text)

Production
- Production Reference ID (text)
- C Reference ID (text) (matches Reagents.Reagent Reference ID)
- P Reference ID (text) (matches Reagents.Reagent Reference ID)

我正在尝试建立一个查询,将C和P的供应商(从试剂)链接到生产参考ID(来自生产),如下所示。

Query Output
- Production Reference ID
- C Supplier
- P Supplier

以下是我到目前为止所得到的内容,但它告诉我我错过了一名操作员。

SELECT C.Supplier as 'C Supplier', P.Supplier as 'P Supplier'
FROM Production
INNER JOIN Reagents AS C ON C.Reagent Reference ID=Production.C Reference ID
INNER JOIN Reagents AS P ON P.Reagent Reagent Reference ID=Production.P Reference ID
WHERE Production.Production Reference ID=?

提前致谢!

2 个答案:

答案 0 :(得分:2)

您可以尝试此方法(这是使用子查询,请注意,如果表很大,它可能会有点慢):

SELECT Production.[Production Reference ID],
(SELECT Reagents.Supplier FROM Reagents WHERE Reagents.[Reagent Reference ID] = Production.[C Reference ID] ) as CSupplier, 
(SELECT Reagents.Supplier FROM Reagents WHERE Reagents.[Reagent Reference ID] = Production.[P Reference ID] ) as PSupplier
FROM Production;

编辑:通过一些测试,我发现它在JOIN中是如何工作的,它比方法1快得多:

SELECT C.Supplier as 'C Supplier', P.Supplier as 'P Supplier'
FROM ( Production
INNER JOIN Reagents AS C ON C.[Reagent Reference Number]=Production.[C Reference Number] )
INNER JOIN Reagents AS P ON P.[Reagent Reagent Reference Number]=Production.[P Reference Number]
WHERE Production.[Production Reference Number]=?

在查询中使用多个JOIN时,MS Access需要括号。

答案 1 :(得分:0)

尝试将字段名封装在方括号[]上,如下所示。

SELECT C.Supplier as 'C Supplier', P.Supplier as 'P Supplier'
FROM Production
INNER JOIN Reagents AS C ON C.[Reagent Reference Number]=Production.[C Reference Number]
INNER JOIN Reagents AS P ON P.[Reagent Reagent Reference Number]=Production.[P Reference Number]
WHERE Production.[Production Reference Number]=?