16.3 删除数据
从数据表中删除数据使用DELETE语句,DELETE语句允许WHERE子句指定删除条件。DELETE语句基本语法格式如下:
DELETE FROM table_name [WHERE <condition>];
table_name指定要执行删除操作的表;“[WHERE <condition>]”为可选参数,指定删除条件,如果没有WHERE子句,DELETE语句将删除表中的所有记录。
【例16.10】在表person中,删除id等于10的记录,SQL语句如下:
执行删除操作前使用SELECT语句查看当前id=10的记录:
mysql> SELECT * FROM person WHERE id=10;
+---- | +-------- | +----- | +---------+ |
id | name | age | info |
+---- | +-------- | +----- | +---------+ |
10 | LiMing | 15 | student |
+---- | +-------- | +----- | +---------+ |
可以看到,现在表中有id=10的记录,下面使用DELETE语句删除记录,语句执行结果如下:
mysql> DELETE FROM person WHERE id = 10; Query OK, 1 row affected (0.02 sec)
语句执行完毕,查看执行结果:
mysql> SELECT * FROM person WHERE id=10; Empty set (0.00 sec)
查询结果为空,说明删除操作成功。
【例16.11】在person表中,使用DELETE语句同时删除多条记录,在前面UPDATE语句中将age字段值在19到22之间的记录的info字段值修改为student,在这里删除这些记录,SQL语句如下:
DELETE FROM person WHERE age BETWEEN 19 AND 22;
执行删除操作前使用SELECT语句查看当前的数据:
mysql> SELECT * FROM person WHERE age BETWEEN 19 AND 22;
+---- | +--------- | +----- | +---------+ |
id | name | age | info |
+---- | +--------- | +----- | +---------+ |
1 | Willam | 20 | student |
3 | Green | 21 | student |
4 | Suse | 22 | student |
6 | Dale | 22 | student |
8 | Harry | 21 | student |
9 | Harriet | 19 | student |
+---- | +--------- | +----- | +---------+ |
可以看到,这些age字段值在19到22之间的记录存在表中。下面使用DELETE删除这些记录:
mysql> DELETE FROM person WHERE age BETWEEN 19 AND 22; Query OK, 6 rows affected (0.00 sec)
语句执行完毕,查看执行结果:
mysql> SELECT * FROM person WHERE age BETWEEN 19 AND 22; Empty set (0.00 sec)
查询结果为空,删除多条记录成功。
【例16.12】删除person表中所有记录,SQL语句如下:
DELETE FROM person;
执行删除操作前使用SELECT语句查看当前的数据:
mysql> SELECT * FROM person;
+---- | +--------- | +----- | +-----------+ |
id | name | age | info |
+---- | +--------- | +----- | +-----------+ |
2 | Laura | 25 | NULL |
5 | Evans | 27 | secretary |
7 | Edison | 28 | singer |
11 | Beckham | 31 | police |
+---- | +--------- | +----- | +-----------+ |
结果显示person表中还有4条记录,执行DELETE语句删除这4条记录:
mysql> DELETE FROM person; Query OK, 4 rows affected (0.00 sec)
语句执行完毕,查看执行结果:
mysql> SELECT * FROM person; Empty set (0.00 sec)
查询结果为空,删除表中所有记录成功,现在person表中已经没有任何数据记录。
提 示
如果想删除表中的所有记录,还可以使用TRUNCATE TABLE语句,TRUNCATE将直接删除原来的表并重新创建一个表,其语法结构为TRUNCATE TABLE table_name。TRUNCATE直接删除表而不是删除记录,因此执行速度比DELETE快。