INSERT小记(insert into select和not in,values括号里不能放select)

情况是这样:

我有两个表,一个inj_wash_pro存主要数据,一个inj_wash_updatelog存的是最后修改时间,有触发器自动触发,但是由于失误,触发器忘了写insert,现在有9122条数据在inj_wash_updatelog里,9157条在inj_wash_pro里,差了35条数据

目的是这样:

写一个insert语句,使pro和updatelog里相差的列同步一下

第一步:写select语句,查两表不同的数据

select t.proid,t.subdate from inj_wash_pro t
where t.proid not in(select g.proid from inj_wash_updatelog g)
要点:not in的使用,可以匹配到存在于pro而不存在于updatelog里的proid,也就是两表的主键

执行后找到了两表相差的列

第二步:写insert语句,把相差列插入到updatelog表里

这里我卡了很久,最后找到了insert into select语句,专门用来复制表的语句

最后正确的语句是:

insert into inj_wash_updatelog g (g.proid,g.update_date)
select t.proid,t.subdate from inj_wash_pro t
where t.proid not in(select g.proid from inj_wash_updatelog g)

在这之前我写过这样的语句

insert into inj_wash_updatelog g (g.proid,g.update_date)
values(select t.proid,t.subdate from inj_wash_pro t
where t.proid not in(select g.proid from inj_wash_updatelog g))
报错是表达式错误,values括号里是不能放select的,我这样的新手应该是常犯这种错误的

也写过这样的语句

insert into inj_wash_updatelog g (g.proid,g.update_date)
values((select t.proid,t.subdate from inj_wash_pro t
where t.proid not in(select g.proid from inj_wash_updatelog g)))
注意括号,报错是列不够,也就是说这样取来values括号里应该是只有一列数的
甚至我还试过with as,就不表了

最后的结论:

复制两表时用insert into select,列对应上,非常轻松


附赠:

同步updatelog表的update_date列:

update inj_wash_updatelog g set g.update_date = (
select nvl(t.washdate,t.subdate) from inj_wash_pro t )
where t.proid = g.proid



  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值