MySQL笔记 插入修改删除
一.插入语句insert
方式一:经典的插入
语法:
insert into 表名(列名,...)
values(值1,...);
特点:
-
插入的值的类型要与列的类型一致或兼容
-
不可以为null的列必须插入值
-
列数和值的个数必须一致
-
可以省略列名,默认所有列,而且列的顺序和表中列的顺序一致
案例:
insert into beauty(id, name, sex) values(13,'唐艺昕','女');
省略列名:
insert into beauty values(18,'张飞','男',null,'119',null,null)
方式二:
语法:
insert into 表名
set 列名=值,列名=值,...
案例:
insert into beauty set id=19,name='刘涛',phone='999';
方式一pk方式二:
-
方式一支持多行插入,方式二不支持
insert into beauty
value(23,'小张',男)
,(21,'小黑',女);
-
方式一支持子查询,方式二不支持
insert into beauty(id,name,phone) select id, boyname, '1234567' from bos where id<3;
二.修改语句update
语法:
修改单表的记录:
update 表名
set 列=新值,列=新值,...
where 筛选条件;
案例:修改beauty表中姓唐的女神的电话为123
update beauty set phone='123' where name like "唐%";
修改多表的记录:
sql92语法:
update 表1 别名,表2 别名
set 列=值,...
where 连接条件
and 筛选条件;
sql99语法:
update 表1 别名
inner|left|right join 表2 别名
on 连接条件
set 列=值,...
where 筛选条件;
三.删除语句delete和truncate
方式一:delete
单表的删除:
语法:
delete from 表名
where 筛选条件
案例:删除手机号以9结尾的女神的信息
delete from beauty where phone like "%9";
多表的删除:
sql92语法:
delete 表1的别名,表2的别名
from 表1 别名,表2 别名
where 连接条件
and 筛选条件;
sql99语法:
delete 表1的别名,表2的别名
from 表1 别名
inner|left|right join 表2 别名
on 连接条件
where 筛选条件;
案例:删除张无忌的女朋友的信息
delete b from beauty b inner join boys bo on b.boyfriend_id=bo.id where bo.boyName='张无忌';
方式二:truncate删除整张表
语法:
truncate table 表名;
方式一delete pk 方式二truncate:
-
delete可以加where条件,truncate不能加
-
truncate删除,效率高一丢丢
-
假如要删除的表中有自增长列,如果用delete删除后,再插入数据,自增长列的值从断点开始,而truncate删除后,再插入数据,自增长列的值从1开始
-
truncate删除后没有返回值,delete删除有返回值
-
truncate删除不能回滚,delete删除可以回滚