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;
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值