简体   繁体   English

Oracle SQL:将选择从一个表插入到另一个表中,其中用户具有带有订单号的多个条目

[英]Oracle SQL: Insert select from one table to another where user has multiple entries with order number

Table A 表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

Table B 表B

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

I would like to insert a row into Table A using the data from Table B and the max order number for that user with the following: 我想使用表B中的数据和该用户的最大订单号通过以下方式在表A中插入一行:
If there is no email address in Table A for that user, insert the email address from Table B with max order number. 如果表A中没有该用户的电子邮件地址,请插入表B中具有最大订单号的电子邮件地址。
If the email in Table A is the same as the email in Table B for that user, do not insert anything. 如果表A中的电子邮件与该用户的表B中的电子邮件相同,则请勿插入任何内容。
If the email in Table A is different from the email in Table B for that user, insert the email address from Table B with max order number. 如果表A中的电子邮件与该用户的表B中的电子邮件不同,请插入表B中具有最大订单号的电子邮件地址。

Output for the above should be insert into Table A* 以上输出应插入表A *

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

I have tried this multiple ways and keep hitting a wall. 我尝试了多种方法,并不断碰壁。 Any suggestions on what route to take? 有什么建议走什么路线?

If I understand correctly, you can do this with a single insert statement: 如果我理解正确,则可以使用一个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
                     );

Note: some of the identifiers you have used, such as order , are reserved words. 注意:您使用的某些标识符(例如order )是保留字。 I haven't bothered to escape them, assuming they are just examples. 假设它们只是示例,我并没有费心逃避它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM