MySql数据库操作语言(插入、修改、删除)

DML语言:数据库操作语言
插入: insert
修改: update
删除: delete

一、插入语句

1. 方式一:

语法:

insert into 表名(列名,...values(1,...);
  1. 插入值的类型要与列的类型一致或者兼容
insert into beauty(id,name,sex,borndate,phone,photo,boyfriend_id) values(13,"唐艺昕","女","1990-4-23","189888888",null,2);
  1. 不可以为null的列必须插入值,可以为null的列如何插入值?
方式一:
insert into beauty(id,name,sex,borndate,phone,photo,boyfriend_id) values(13,"唐艺昕","女","1990-4-23","189888888",null,2);
方式二:
insert into beauty(id,name,sex,borndate,phone,boyfriend_id) values(14,"董璇","女","1980-4-40","1382888888",3);
  1. 列的顺序是否可以调换(可以)
insert into beauty(name,sex,id,phone) values("蒋欣","女",16,"110");
  1. 列数和值的个数必须一致
insert into beauty(name,sex,id,phone) values("关晓彤","女") //会报错,列数和值的个数不一致
  1. 可以省略列名,默认所有列,而且列的顺序和表中列的顺序一致
insert into beauty values(18,"张飞","男",null,"119",null,null);
2. 方式二:

语法:

insert into 表名
set 列名=,列名=,...
insert into beauty set id=19,name="刘涛",phone="9999";

两种插入方式比较:

  1. 方式一支持插入多行,方式二不支持
insert into beauty(id,name,sex,borndate,phone,photo,boyfriend_id) 
values(24,"唐艺昕1","女","1990-4-23","189888888",null,2),
(25,"唐艺昕1","女","1990-4-23","189888888",null,2),
(26,"唐艺昕2","女","1990-4-23","189888888",null,2);
  1. 方式一支持子查询,方式二不支持
insert into beauty(id,name,phone) select 26,"宋茜","118098641";
insert into beauty(id,name,phone) select id,boyname,"123456" from boys where id < 3;

二、修改语句

1. 修改单表的记录
语法:
update 表名
set=新值,=新值...
where 筛选条件;
  1. 修改beauty表中姓唐的女神的电话为 1388998887;
update beauty set phone = "1388998887" where name like "唐%";
  1. 修改boys表中id号为2的名称为张飞,魅力值 10
update boys set boyname = "张飞",usercp = 10 where id = 2;
2. 修改多表的记录
//sql92语法:
update1 别名,2 别名
set=,....
where 连接条件
and 筛选条件;
//sql99语法:
update1 别名
inner | left | right join2 别名
on 连接条件
set=,...
where 筛选条件
  1. 修改张无忌的女盆友的手机号为114
update boys bo inner join beauty b on bo."id" = b."boyfriend_id"
set b."phone" = "114" where bo."boyName" = "张无忌";
  1. 修改没有男盆友的女神的男盆友编号都为2号
update boys bo right join b on bo."id" = b."boyfriend_id"
set b."boyfriend_id" = 2
where b."id" is null;

三、删除语句

1. 方式一 : delete
//单表的删除
delete from 表名 where 筛选条件;
//多表的删除
sql92语法:
delete1的别名,2的别名
from1 别名,2 别名
where 筛选条件
and 筛选条件
sql99语法:
delete1的别名,2的别名
from1 别名
inner | left | right join2 别名 on 连接条件
where 筛选条件
  1. 删除手机号以9结尾的女神信息(单表的删除
delete from beauty where phone like "%9";
  1. 删除张无忌的女盆友信息(多表的删除
delete b from beauty b
inner join boys bo on b."boyfriend_id" = bo."id"
where bo."boyName" = "张无忌";
  1. 删除黄晓明的信息以及他女盆友的信息 (多表的删除)
delete b,bo from beauty b
inner join boys bo on b."boyfriend_id" = bo."id"
where bo."boyName" = "黄晓明";
2. 方式二 : truncate(清空)
truncate table 表名;		//全部删除
  1. 将魅力值 > 100 的男神信息删除
truncate table boys;	//将整个表的数据清空

两种方式的比较:
① delete 可以加 where 筛选条件 ,truncate 不能加
② truncate 删除效率更高(没有筛选条件)
如果要删除的表中有自增长列 : 用delete 删除后,再插入数据,自增长列的值从断点开始;而 truncate删除后,再插入数据,自增长列的值从1 开始
④ truncate 删除后没有返回值,delete删除有返回值
⑤ truncate 删除不能回滚,delete 删除可以回滚

猜你喜欢

转载自blog.csdn.net/weixin_38739598/article/details/107127700