mysql笔记(10)-数据的插入和更新(insert/update/case)

本文将简单介绍数据的插入和更新,包括关键字insert、update、case等

一、插入数据

常见的插入方式有以下几种:

1、insert into + set
insert into table_name
set column1=value1, column2=value2, column3=value3;

这种方式每次只能插入一行
且set从句内的values不能全部为空

2、insert into + values
insert into table_name
(column1, column2, column3)
values
(value01, value02, value03),
(value11, value12, value13);  

这种方式可以一次性插入多行
不同行之间的数据要用逗号进行分隔

3、replace into + values

replace into table_name
(column1, column2, column3)
values
(value1, value2, value3);

这种方式用于替换表中的某一行
若新插入记录的主码已经存在于表中,则用新记录替换旧记录
若新插入记录的主码不在表中,则直接插入新记录

二、更新数据

普通的update语句写法如下:

update table_name
set column1=value1, column2=value2
where xxx;

例如:在instructor(教师信息)表中
我们想更新 ID为10101的教师的工资为70000

update instructor
set salary=70000
where ID=10101;

对于更复杂的数据更新 我们可以添加case-when从句
从而实现对数据的分类更新

update table_name
set column_name=case
when condition1 then result1
when condition2 then result2
else result3
end;

例如:在instructor(教师信息)表中 对所有教师进行涨薪
对工资小于等于100000的涨薪5%,其他人涨薪3%

update instructor
set salary=case
when salary<=100000 then salary*1.05
else salary*1.03
end;
原文地址:https://www.cnblogs.com/baebae996/p/12912887.html