技术分享-SQL-(2)更新与插入

本期主要函数有三:

insert、update和merge into

 

首先我们利用上次的数据表简历两份新表,数据表链接:https://download.csdn.net/download/weixin_42078618/10555285

在mysql:

create table goodsinfo_1 select * from tmp.goodsinfo where the_month=201805;

create table goodsinfo_2 select * from tmp.goodsinfo where the_month=201806;

在sqlserver:


select * into tmp.dbo.goodsinfo_1 from tmp.dbo.goodsinfo where the_month=201805

select * into tmp.dbo.goodsinfo_2 from tmp.dbo.goodsinfo where the_month=201806

 

我们把5、6月的数据分别取出来作为练习表,这次试用mysql来学习

 

1、首先,insert

(1)把1表的所有插入2表

insert into tmp.goodsinfo_2 
select * from tmp.goodsinfo_1;

要想指定插入的字段,需要这么写,如我我只插入两个字段

insert into tmp.goodsinfo_2 (goodsid, goodsname)
select goodsid, goodsname from tmp.goodsinfo_1;

然后还可以指定值:

insert into tmp.goodsinfo_2 (goodsid, goodsname)
value('110','警察局')

在mysql,插入多行可以这么写

insert into tmp.goodsinfo_2 (goodsid, goodsname)
values('110','警察局'),('120','医院')

但是sqlserver不支持这么写

 

2、update

(1)简单更新

update tmp.goodsinfo_2 
set goodsname='iphone x'
where the_month=201806

把201806的商品名全部变成‘iphone x’。。。

 

(2)连表更新

把1和2两个表有相同goodsid的2表商品名字更新到1表

mysql:

update tmp.goodsinfo_2 a
inner join tmp.goodsinfo_1 as  b
on a.goodsid=b.goodsid
set a.goodsname=b.goodsname

sqlserver:

update a
set a.goodsname=b.goodsname
from tmp.dbo.goodsinfo_2 a
inner join tmp.dbo.goodsinfo_1 b
on a.goodsid=b.goodsid

另外还有exists存在性更新方法,请大家自行查阅,这种方法相对比较少用,以及有left join、right join、full join以及cross join等连表方法,这里就不一一举例了

同时,insert也有类似于update连表的方法,可以连表插入

 

2、merge into

mysql是没有merge into功能的,其实row_number()也没有。。。

所以以sqlserver举例

 

merge into tmp.dbo.goodsinfo_2 a
using tmp.dbo.goodsinfo_1 b 
on a.goodsid=b.goodsid
when matched then update set a.goodsname=b.goodsname
when not matched then insert values(.....)

该语句的用法是update和insert的一种结合,即:若存在则更新,若不存在则插入

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值