一、delete
- 作用:可用于删除表中某一行或多行(所有行),但不影响表结构、熟悉、索引。通俗而言:把表当作一个装东西的箱子,delete作用只是把箱子东西剔除,而不扔掉箱子也不影响箱子的内部架构。
- 语法 :
删除单行,按照某个筛选条件(值唯一,否则删除多行)
delete from 表名 where 列名=值;
删除多行,按照某个筛选条件(多个值)
delete from 表名 where 列名=值1 or 列名=值2;
若列名相同还可以用下列表示
delete from 表名 where 列名in(值1,值2)
删除所有行
delete from 表名
或
delete *from 表名
例:
1、删除单行——删除学生表(表名:student)中 学号(id_num)为10的学生信息
delete from student where id_num=10;
2、 删除多行——删除学生表(表名:student)中 学号(id_num)为10和5的学生信息
delete from student where id_num=10 or id_num=5;
或者
delete from student where id_num in(10,5);
3、删除学生表中所有行(也可以说成所有列),即删除表中所有学生信息,后续可以继续插入。
delete from student
delete *from student
二、drop
- 作用:用于删除整表(整个表结构、属性、索引都会被删除)。通俗而言:把表当作一个装东西的箱子,drop作用把整个箱子全部扔掉,包括箱子中的东西。
- 语法
删除表
drop table 表名
例:
删除学生表(student),后续不可再插入信息,需要重新建表。
drop table student
三、truncate
- 作用:用于删除表内数据,但是保留了表结构,类似于delete from 表名
- 语法
truncate table 表名
例:
删除学生表(student)中信息,后续可以继续插入信息。
truncate table student
等同于
delete *from student
或
delete from student
四、作用场景与区别
- 无需表中所有信息与该表:使用drop
- 无需表中信息但需要保留i表,用truncate或者delete from table;
- 删除表中部分信息,使用delete
delete、truncate与drop区别:是否删除表结构、索引、属性
delete与truncate的区别:两者都可以用于删除全表信息,且不删除表结构、索引与属性,但是对于有主外键关系的表,不能使用truncate而应该使用delete语句,这是由于truncate不记录在日志中,不能够激活触发器
小结
delete和truncate都可以删除表信息而不影响表结构,drop直接删除整个表,包括表结构、索引、属性,truncate和delete区别在于对有主外键关系的表,不能使用truncate。