添加
插入记录
insert [into] 表名 [字段名] values (字段值);
# insert into 表名:表示往哪张表中添加数据
# (字段名 1, 字段名 2, ...):要给哪些字段设置值
# values (值 1, 值 2, ...):设置具体的值
插入全部字段
-- 所有的字段名都写出来
insert into 表名 (字段名 1, 字段名 2, 字段名 3...) values (值 1, 值 2, 值 3...);
-- 不写字段名
insert into 表名 values (值 1, 值 2, 值 3...);
插入部分字段
insert into 表名 (字段名 1, 字段名 2, ...) values (值 1, 值 2, ...);
没有添加数据的字段会使用null
补充-蠕虫复制
蠕虫复制:将一张已经存在的表中的数据复制到另一张表中。
#格式(将表2中所有列复制到表1)
insert into 表名1 select * from 表名2
#将表2中部分列复制到表1
insert into 表名1(列 1, 列 2) select 列1, 列2 from 表名2;
举例
#创建 student2 表,student2 结构和 student 表结构⼀样
drop table student2;
create table student2 like student;
#将 student 表中的数据添加到 student2 表中
insert into student2 select * from student;
#如果只想复制 student 表中 name,age 字段数据到 student2 表中,两张表都写出相应的列名
insert into student2 (name,age) select name,age from student;
select * from student2;
修改
更新表记录
update 表名 set 列名=值 [where 条件表达式]
# update: 需要更新的表名
# set: 修改的列值
# where: 符合条件的记录才更新
# 可以同时更新⼀个或多个字段。
# 可以在 where ⼦句中指定任何条件。
不带条件修改数据
update 表名 set 字段名=值; -- 修改所有的⾏
带条件修改数据
update 表名 set 字段名=值 where 字段名=值;
具体操作
#不带条件修改数据,将所有的性别改成⼥
update student set sex = '⼥';
#带条件修改数据,将 id 号为 2 的学⽣性别改成男
update student set sex='男' where id=2;
# ⼀次修改多个列,把 id 为 3 的学⽣,年龄改成 26 岁,address 改成北京
update student set age=26, address='北京' where id=3;
删除
删除表记录
delete from 表名 [where 条件表达式]
# 如果没有指定 where ⼦句,MySQL 表中的所有记录将被删除。
# 可以在 where ⼦句中指定任何条件
不带条件删除
delete from 表名;
带条件删除
delete from 表名 where 字段名=值;
使用truncate删除表中所有记录
truncate table 表名;
truncate和delete的区别
truncate相当于删除表的结构,再创建一张表。