MySQL删除命令_DELETE

时间:2022-02-27 10:35:56

单表删除语句:

DELETE [LOW_PRIORITY][IGNORE] FROM tbl_name

    [WHERE where_definition]
    [ORDER BY ...]
    [LIMIT row_count]
这里只对delete的常用参数及用法做出介绍。

说明:

low_priority:强制delete命令被延迟执行,直到没有其它客户端读取本表时再执行。

ignore:使MySQL忽略delete执行所有的错误,而错误会以警告的方式返回。

order by...:表中记录按照指定的顺序进行删除,此子句一般与limit联用才有意义。

limit:指定删除操作的指定行范围。

注意:1)不能把ORDER BY或LIMIT与multiple-table UPDATE(多表更新)同时使用;

           2)当delete伴随有多个限制条件时,是将多个限制条件执行查询操作后,再执行对应的删除操作。

(1)简单单表删除

语句:delete from table_name where [条件]

示例:

mysql> select * from staff;
+----+----------+-------+
| id | name | slary |
+----+----------+-------+
| | guoding | |
| | dingtao | |
| | haofugui | |
| | guoming | |
| | haotian | |
| | fengfei | |
| | guoting | |
| | guoding | |
| | xiaohua | |
+----+----------+-------+
rows in set (0.00 sec) mysql> delete from staff where id=9; //通过where指定要删除的记录或记录组合
Query OK, row affected (0.00 sec) mysql> select * from staff;
+----+----------+-------+
| id | name | slary |
+----+----------+-------+
| | guoding | |
| | dingtao | |
| | haofugui | |
| | guoming | |
| | haotian | |
| | fengfei | |
| | guoting | |
| | guoding | |
+----+----------+-------+
rows in set (0.00 sec)

(2)删除-排序、限制

order by...一般与limit搭配使用才有意义。

如:删除工资最低的记录

mysql> select * from staff;
+----+----------+-------+
| id | name | slary |
+----+----------+-------+
| | guoding | |
| | dingtao | |
| | haofugui | |
| | guoming | |
| | haotian | |
| | fengfei | |
| | guoting | |
| | guoding | |
+----+----------+-------+
rows in set (0.00 sec) mysql> delete from staff order by slary asc limit 1; //删除工资最低的数据记录
Query OK, row affected (0.00 sec) mysql> select * from staff;
+----+----------+-------+
| id | name | slary |
+----+----------+-------+
| | guoding | |
| | dingtao | |
| | haofugui | |
| | guoming | |
| | haotian | |
| | fengfei | |
| | guoding | |
+----+----------+-------+
rows in set (0.00 sec)

(3)连接删除

假设有一个post表与staff对应:

mysql> select * from staff;
+----+----------+-------+
| id | name | slary |
+----+----------+-------+
| | guoding | |
| | dingtao | |
| | haofugui | |
| | guoming | |
| | haotian | |
| | fengfei | |
| | guoding | |
+----+----------+-------+
rows in set (0.00 sec) mysql> select * from post;
+-----+----------+-------+
| num | name | level |
+-----+----------+-------+
| | haotian | |
| | guoming | |
| | haofugui | |
+-----+----------+-------+
rows in set (0.00 sec)

现在需要从表staff中删除在post没有对应记录的记录:

mysql> delete staff from staff left join post on staff.name=post.name where post.name is NULL;
Query OK, rows affected (0.00 sec) mysql> select * from staff;
+----+----------+-------+
| id | name | slary |
+----+----------+-------+
| | haofugui | |
| | guoming | |
| | haotian | |
+----+----------+-------+
rows in set (0.00 sec)

在上述删除命令中,也可以引入别名,方便输入,如:

mysql> delete A from staff as A left join post as B on A.name=B.name where B.name is NULL;

注意:NULL不可以用等号(B.name=NULL),正确的应该是B.name is NULL