Oracle SQL:加入此查询的正确方法?
我有三个不同的表,我试图正确连接它们,但遇到了一些问题。
以下是表格
- 火车:火车列表 (choo-choooo) 和火车长度(以车厢数量表示)
- WTA:车厢吨数 A - 位置 A 处火车车厢的重量
- B 车厢内车厢的重量
WTB:车厢吨数 B -位置 问题:WagonTonnes 表中的一个/或/两个表中随机丢失了一些整列列车。 WagonTonnes 表中缺少一些单独的货车。我希望我的查询将这些缺失的情况显示为 null。
我第一次尝试这样做并且效果很好。
select
train.id,
train.length,
a.position_in_train
a.tonnes,
from
train
left outer join wta a
using (train_id)
现在我想为 b 添加一个左外连接,就像这样
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)
但这会变得混乱并一遍又一遍地重复相同的行结果。
建议的解决方案
我怀疑我需要以某种方式从火车获取查询,而不是看起来像这样,
train.id train.length
7 163
而是看起来像
train.id train.position
7 1
7 2
7 3
7 4
... ...
7 162
7 163
这样,然后重写我的连接,如下所示:
left outer join wta a
on (a.train_id = train.train_id and a.position = train.position)
问题1:是我的吗解决这个问题的一般方法正确吗? (join-wise)
问题2:我的解决方案正确吗?如果是这样,我该如何实施?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的方法会起作用,但我认为 LEFT JOIN 到代表 WTA 和 WTB 超集的组合数据集更容易。由两部分组成的 UNION ALL 模拟了 MySQL 中所缺少的 FULL JOIN。
脑子冻结了,对于 Oracle,FULL JOIN 是(内部查询)
Your approach will work, but I think it is easier to LEFT JOIN to a combined dataset representing the superset of WTA and WTB. The two-part UNION ALL emulates FULL JOIN that is lacking in MySQL.
Brain freeze, for Oracle, the FULL JOIN would be (inner query)