Skip to main content

删除记录

DELETE FROM

Syntax
DELETE FROM table_name
WHERE conditions;

没有 WHERE 条件是清空全表内容,比较危险。

Example
DELETE FROM tb_student WHERE stu_id = 1004;
DELETE FROM tb_student WHERE stu_id = 1002 OR stu_id = 1003;
DELETE FROM tb_student WHERE stu_id IN (1002, 1003);
  • 删除条件比较常用的是主键列,可以精确定位
  • = 是比较运算符,不是赋值
  • IN 是成员运算符

Safe update mode

DELETE FROM tb_student 

MySQL 默认开启“Safe update mode”,清空全表的时候会报错,阻止你清空全表。可以关闭这个模式,但不建议:

SHOW VARIABLES LIKE '%safe%';
4ewHSK

Delete record with foreign key constraint

如果删除的表有外键约束,且指向的表中有这条数据,删除的时候会报错。

stu_idstu_namestu_genderstu_birthcol_id
1001JackMale02/26/1995101
col_idcol_namecol_tel
101'计算机学院''021-12345678'
102'外国语学院''021-12345679'
DELETE FROM tb_college WHERE col_id = 101; # OK
DELETE FROM tb_college WHERE col_id = 103; # ERROR

如果非要删除 tb_college 表中的 103 数据,就需要先修改 tb_student 表中的外键约束:

ALTER TABLE tb_student DROP CONSTRAINT fk_student_cid;

ALTER TABLE tb_student ADD CONSTRAINT fk_student_cid
FOREIGN KEY (col_id) REFERENCES tb_college (col_id)
# default: 如果 tb_student 中有属于这个学院的学生,就不让删除这个学院
ON DELETE RESTRICT;

如果 tb_student 中有属于这个学院的学生,删这个学院学院的时候,tb_student 表也会删除这个学生:

ON DELETE CASCADE;

如果 tb_student 中有属于这个学院的学生,删这个学院学院的时候,tb_student 表也这个学生 col_id 列会设为空值,前提是该列允许设置为空:

ON DELETE SET NULL;
tip

定义外键约束的时候,推荐使用默认的 RESTRICT,比较安全,平时很少使用。