删除数据——delete
# 删除数据
# 方式一
delete from <TableName> where <Conditions>;
1
Condition如何设置将决定会删除哪些数据,一条或者多条,所以要谨慎设置。通常会根据唯一的去选。
# 方式二
delete from <TableName> where <Condition1> and <Condition2>;
1
delete from <TableName> where <Condition1> or <Condition2>;
1
使用 and
或 or
关键字。
# Example
一:删除student表中 id
为 3 的数据
delete from student where id=3;
1
二:删除student表中 age
小于 18 的数据
delete from student where age<18;
1
三:下面可以清空整个student表的数据,但清空表不建议这样写,因为它会遍历每一条数据,会很慢!
delete from student;
1
清空表更快的方法是 truncate table <TableName>
。
# 反例 -关于条件一定要根据唯一的来选,否则殃及池鱼
有如下一张表:
+----+------+------+
| id | name | age |
+----+------+------+
| 1 | Tom | 10 |
| 2 | Tom | 18 |
| 3 | Tom | 20 |
| 4 | Jim | 20 |
+----+------+------+
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
按如下方式删除:
delete from student where name='Tom';
1
最后表只剩下一条数据了。。。
+----+------+------+
| id | name | age |
+----+------+------+
| 4 | Jim | 20 |
+----+------+------+
1
2
3
4
5
2
3
4
5
编辑 (opens new window)
上次更新: 2022/09/26, 16:55:15