Oracle中插入数据由查询所得

Oracle中插入数据由查询所得

  • Oracle中的插入语法一
    insert into 表名 values ( , , , );
    【使用情景】手动输入

  • Oracle中的插入语法二:
    insert into 表名 select子句;
    【使用情景】由查询出来的结果插入表中

下面是一个案例,将select出的结果插入表中

一家银行发行了新的信用卡,刚开始的时候推广的很好,但是逐渐废卡也越来越多
废卡:卡上余额少于2元,并且用户长期不使用该卡
因此银行在二月份把这些废卡都从数据库中删除了,但是很快问题就来了,
–用户发现他的卡再也不能使用而投诉,因此只能再把这些卡恢复

--用户表
create table cust(
   cardid int primary key,
   cname varchar2(50)
)segment creation immediate;
--账户表
create sequence seq_account_id;
create table accounts(
   accountid int primary key ,
   cardid int references cust(cardid) ,
   score int
)segment creation immediate;


insert into cust values(16,'张三');
insert into cust values(23,'李四');
insert into cust values(25,'王五');
insert into cust values(29,'刘六');
insert into cust values(30,'杨七');

insert into accounts values(seq_account_id.nextval,16,3400);
insert into accounts values(seq_account_id.nextval,25,4565);
insert into accounts values(seq_account_id.nextval,29,456);

select * from cust;
select * from accounts;

解决方案:

  • 使用左外连 left join 将哪些用户的卡被删除了
  • 再使用 insert into 表名 select 子句 将卡添加进去
insert into accounts 
       select  seq_account_id.nextval,cust.cardid,2
       from cust left join accounts 
       on cust.cardid = accounts.cardid
where score is null;

select * from accounts;

版权声明:本文为m0_48577385原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。