访问查询将多对多记录合并为一行

时间:2014-08-01 13:58:17

标签: sql ms-access

这应该很容易,但我很难过。

我有多对多的关系,例如,许多汽车可以有很多组件。

Don't mind the relationships, this is a screenshot of a query, not the relationships

所以我想要一个查询来返回所有汽车和后续使用的组件。如果没有使用组件,它应该只返回一个NULL值。

Car | Engine  | Tyre
----------------------
1   | Engine3 |
2   | Engine4 | Tyre3
3   | Engine1 | Tyre1

但是使用以下SQL:

SELECT Car.idCar, Engine.idEngine, Tyre.idTyre
FROM ((Component 
RIGHT JOIN (Car 
LEFT JOIN Car_Component ON Car.idCar = Car_Component.idCar) ON Component.idComponent = Car_Component.idComponent) 
LEFT JOIN Engine ON Component.idComponent = Engine.idComponent) 
LEFT JOIN Tyre ON Component.idComponent = Tyre.idComponent;

我明白了:

Car | Engine  | Tyre
----------------------
1   | Engine3 | 
2   | Engine4 | 
2   |         | Tyre3
3   | Engine1 | 
3   |         | Tyre1

我一直在寻找一个解决方案已经有一段时间了,我很确定我需要制作子查询,但我对子查询的了解有限,我不知道如何开始。

Here is the problem in SQL Fiddle.

1 个答案:

答案 0 :(得分:0)

以下查询是否适合您SQL Fiddle

SELECT DISTINCT Car.idCar, Engine.idEngine, Tyre.idTyre
FROM (((Car 
INNER JOIN Car_Component ON Car.idCar = Car_Component.idCar) 
INNER JOIN Component ON Car_Component.idComponent = Component.idComponent) 
LEFT JOIN Engine ON Component.idComponent = Engine.idComponent)
LEFT JOIN Tyre ON Component.idComponent = Tyre.idComponent;