Oracle SQL:将select从一个表插入到另一个表,其中用户有多个带有订单号的表项



表A

User | Order | Type | Contact
1001, 2, email, ijk@test.com
1001, 1, cell, 1234567890
1001, 3, home, 9876543210
1002, 1, home, 1234567891
1002, 2, cell, 1987654321
1003, 1, email, abc@test.com
表B

User | Email
1001, def@test.com
1002, geh@test.com
1003, abc@test.com

我想在表a中插入一行,使用表B中的数据和该用户的最大订单号,如下所示:
如果表A中没有该用户的电子邮件地址,则插入表B中的电子邮件地址和最大订单号。
如果表A中的电子邮件与表B中的电子邮件相同,则不插入任何内容。
如果该用户在表A中的电子邮件地址与表B中的电子邮件地址不同,则插入表B中带有最大订单号的电子邮件地址。

上述输出应插入到表A*

1001, 4, email, def@test.com
1002, 3, email, geh@test.com

我已经尝试了很多方法,但一直碰壁。有什么建议吗?

如果我理解正确的话,您可以使用单个insert语句来完成此操作:

insert into tableA(user, order, type, contact)
    select user, maxorder + 1, 'email', email
    from tableB b cross join
         (select max(order) as maxorder from tableA) const
    where not exists (select 1
                      from tableA a
                      where b.user = a.user and b.contact = a.contact
                     );

注意:您使用的一些标识符,如order,是保留字。我没有费心去回避它们,假设它们只是示例。

相关内容

最新更新