为了练习SQL,我在MS Access中创建了一个测试数据库。它存储有关汽车商店业务的信息。布局如下:
我已使用JOIN
和repairs
cars
services
表成功构建了一个查询:
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';
现在我想将客户信息添加到该查询中,例如显示上面的信息和客户的姓氏。但是,看到repairs
和customers
之间没有直接关系,我只能JOIN
这两张表,我不知所措至于如何构建查询。
感谢您的帮助。
答案 0 :(得分:1)
加入时您还需要考虑汽车,因此您的查询将是:
SELECT cu.lastName
FROM ((customers cu INNER JOIN cars ca
ON cu.id = ca.customerId)
INNER JOIN replairs r
ON r.carNumber = ca.carNumber)
答案 1 :(得分:1)
要连接没有直接关系的表格,您只需加入两者之间的表格。
由于您已经加入了介于两者之间的cars
表,因此您可以加入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';