I have a three different tables that I'm trying to join up correctly but I'm running into some issues.
Here are the tables
- Train: Listing of trains (choo-choooo) and train length in number of wagons
- WTA: Wagon Tonnes A - Weight of wagons in train at Location A
- WTB: Wagon Tonnes B - Weight of wagons in train at Location B
The issue: Some entire Trains are missing randomly from either/or/both of the WagonTonnes tables. Some individual wagons are missing from the the WagonTonnes tables. And I want my query to show those cases as null where missing.
I first tried doing this and it works fine.
select
train.id,
train.length,
a.position_in_train
a.tonnes,
from
train
left outer join wta a
using (train_id)
Now I want to add a left outer join for b, like so
select
train.id,
train.length,
a.position_in_train
a.tonnes,
b.position_in_train,
b.tonnes
from
train
left outer join wta a
using (train_id)
left outer join wtb b
using (train_id)
But this goes haywire and repeats the same row result over and over.
Proposed Solution
I suspect that I somehow need to get a query from train that instead of looking like so,
train.id train.length
7 163
looks like this instead
train.id train.position
7 1
7 2
7 3
7 4
... ...
7 162
7 163
And then rewrite my joins to look like this:
left outer join wta a
on (a.train_id = train.train_id and a.position = train.position)
Question 1: Is my general approach to this problem correct? (join-wise)
Question 2: Is my solution correct? If so, how can I implement it?