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

来源:互联网 发布:医学必备数据分析软件 编辑:程序博客网 时间:2024/05/19 06:35

情况是这样:

我有两个表,一个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 twhere 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 twhere 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 twhere 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 twhere 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



0 0