JOIN 没有直接关系的表

JOIN tables with no direct relation

为了练习SQL,我在MS Access 中创建了一个测试数据库。它存储有关汽车商店业务的信息。布局是这样的:

我已经成功构建了对 JOIN repairs table 的查询 carsservices:

SELECT cars.[Make], cars.[Year of production], services.[Service name]
FROM ( repairs 
INNER JOIN cars ON repairs.[Car number]=cars.[Car number] ) 
INNER JOIN services ON repairs.[Service ID]=services.ID
WHERE cars.[Color]='Red';

现在我想将客户信息添加到该查询中,例如显示上面的信息和客户的姓氏。但是,看到 repairscustomers 之间没有直接关系,我不能只 JOIN 这两个 table,我不知道如何构建查询。

感谢您的帮助。

加入时您还需要考虑汽车,因此您的查询将是:

SELECT cu.lastName
FROM ((customers cu INNER JOIN cars ca
ON cu.id = ca.customerId)
INNER JOIN replairs r
ON r.carNumber = ca.carNumber)

要加入没有直接关系的 table,您只需加入中间的 table。

因为您已经加入了介于两者之间的 cars table,您可以直接加入 customers。重新排列联接,以便获得从一端到另一端的链:

SELECT
  cars.[Make], cars.[Year of production],
  services.[Service name],
  customers.[First Name], customers.[Last Name]
FROM
  (
    (
      services
      INNER JOIN repairs on repairs.[Service ID] = services.ID
    )
    INNER JOIN cars ON cars.[Car number] = repairs.[Car number]
  )
  INNER JOIN customers on customers.[ID] = cars.[Customer ID]
WHERE
  cars.[Color] = 'Red';