DML(数据操纵)语言的学习
注意:以上为employees表、departments表、locations表、job_grades表、jobs表
目录:
- 插入(insert)
- 修改(update)
- 删除(delete)
一、插入语句
第一种语法:
表名 列名 新值
insert into 表名(列名,…) values(值1,…);
1、插入的值的类型要与列的类型一致或兼容
insert into student(id,name,sex,borndate,phone)
values(1,'小明','男','1996-5-3',null);
2、不可以为null的列必须插入值,可以为null的列如何插入值?
方式一:在插入新值中设置为null
insert into student(id,name,sex,borndate,phone)
values(1,'小明','男','1996-5-3',null);
方式二:删除值为空的列名
insert into student(id,name,sex,borndate) values(1,'小明','男','1996-5-3');
3、列的顺序是否可以调换(可以)
insert into beauty(name,sex,id,phone )
values('小红','男','123');
4、列数和值的个数必须一致
insert into beauty(name,sex,id,phone )
values('小红','男','123');
5、可以省略列名,默认所有列,而且列的顺序和表中列的顺序一致
insert into boy values('1','李三','男',null,null);
第二种语法:
insert into 表名 set 列名=值,列名=值,…
例如:
insert into boy set id=19,name='李四';
两种方式大pk
1、方式一支持插入多行
insert into boy values('1','李三','男',null,null),
values('2','李三','男',null,null),
values('3','李三','男',null,null);
2、方式一支持子查询,方式二不支持
insert into boy(id,name,phone) select 26,'黎明','123555' union select 27,'黎明2','123555' union select 37,'黎明3','123555';
二、修改语句
1、 修改单表的记录
语法:
update 表名 set 列=新值,列=新值… where 筛选条件;
2、 修改多表的记录
语法:
sql92语法
update 表1 别名,表2 别名
set 列=值,…
where 连接条件
and 筛序条件
sql99语法
update 表1 别名
inner|left|right join 表2 别名
on 连接条件
set 列=值,…
where 筛选条件
1、修改单表的记录
案例1:修改boy表中姓李的电话修改为123456789
update boy set phone='123456789' where name like '李%';
2、修改多表的记录
案例1:修改李四的女朋友的手机号为211;
update boys b inner join girl g on b.id=g.boy_id
set phone='211' where b.name='李四';
案例2:修改没有男朋友的女神的男朋友编号都为2号
update boys b right join girls g on b.id=g.boy_id
set g.boy_id=2 where g.boy_id is null;
三、删除语句
方式一: delete
语法:
1、单表的删除
delete from 表名 where 筛选条件
2、 多表的删除
sql92语法:
delete 别名
from 表1 别名,表2 别名
where 连接条件
and 筛选条件;
sql99语法:
delete 表1的别名,表2的别名(表1,表2的别名指的是删除对应表的内容)
from 表1 别名
inner|left|right join 表2 别名 on 连接条件
where 筛选条件;
方式二: truncate
语法:truncate table 表名;
方式一: delete
1、 单表的删除
案例1:删除手机号以9结尾的女神信息
delete from girls where phone like '%9';
2、多表的删除
案例1:删除小明的女朋友的信息
delete g from girls g inner join boys b on g.boy_id=b.id
where b.name='小明';
案例2:删除小李的信息以及他女朋友的信息
delete g ,b from girls g join boys b on g.boy_id=b.id
where b.name='小李';
方式二: truncate语句
案例:将全部男生信息删除
truncate table boys;
delete pk truncate
1、 delete可以加where条件,truncate不能加
2、 truncate删除,效率高一点点
3、 假如要删除的表中有自增长列,如果用delete删除后,再插入数据,自增长列的值从断点开始,
4、truncate删除后,再插入数据,自增长列的值从1开始
5、truncate删除不能回滚,delete删除可以回滚