gpt4 book ai didi

sql - 使用来自另一个具有重复项的表中的数据更新 oracle 中的表

转载 作者:行者123 更新时间:2023-12-01 14:09:35 30 4
gpt4 key购买 nike

我有两个 Oracle 表,表 car 和表汽车。我正在更新 Car 以添加汽车品牌和型号中存在的两个字段。两个表都有 3 个外键,代码 1、代码 2 和代码 3,它们将它们链接起来,我需要至少 1 个键来匹配更新表,并且列可以是空白的,所以我们必须小心。除了我在下面提到的重复的情况外,每个记录的代码都是唯一的。为了形象化,让我在这里制作表格:

table 车

   ID | Code1 | Code2| Code3| Color | Salesman
1 1A2B3C 555HGG H1H1H1 Red John
2 2H4H6H 777JHH J1J1J1 Blue Steve
3 3J7K4A 222QYY I1I1I1 Yellow Maria
4 K2K2K2 Pink Clara
5 999YII Red Tim

表汽车
Code1| Code2| Code3 | Make  | Model  | ID
1A2B3C 555HGG H1H1H1 Nissan Sentra 234
2H4H6H J1J1J1 Chevy Malibu 235
K2K2K2 Nissan Maxima 236
K2K2K2 Nissan Maxima 237
999YII Ford Focus 238

更新 table 车:
   ID | Code1 | Code2| Code3| Color | Salesman | Make | Model
1 1A2B3C 555HGG H1H1H1 Red John Nissan Sentra
2 2H4H6H 777JHH J1J1J1 Blue Steve Chevy Malibu
3 3J7K4A 222QYY I1I1I1 Yellow Maria
4 K2K2K2 Pink Clara Nissan Maxima
5 999YII Red Tim Ford Focus

所以 Table Car 最初没有 Make 和 Model 字段,但我们需要从汽车表中获取。假设字段现在存在于表中并且只需要填充。正如您在表格汽车中的 Nissan Maxima 示例中看到的那样,具有唯一 ID 的重复记录也是可能的。在这种情况下,我只需要其中一条记录无关紧要,因为来自汽车的 ID 无关紧要且不需要。两个 ID 字段没有联系。将填充至少 1 个代码字段,永远不会出现全部为空的情况。我知道这是一个有点困惑的问题,所以如果您需要澄清,请询问,我将对我的 OP 进行调整。同样,这也是针对 Oracle 的,所以请记住这一点。任何帮助将不胜感激,这已经困扰我好几天了。

最佳答案

以下使用row_number()得到一行然后匹配代码:

select c.*, a.make, a.model
from car c left join
(select a.*,
row_number() over (partition by code1, code2, code3 order by id) as seqnum
from automobile a
) a
on (c.code1 = a.code1 or c.code1 is null and a.code1 is null) and
(c.code2 = a.code2 or c.code2 is null and a.code2 is null) and
(c.code3 = a.code2 or c.code3 is null and a.code3 is null) and
a.seqnum = 1

关于sql - 使用来自另一个具有重复项的表中的数据更新 oracle 中的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41574927/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com