当前位置: 首页 > 工具软件 > delete > 使用案例 >

MySQL delete 语句

孟英光
2023-12-01

mysql 中delete语句主要分为三个层次,下面简单介绍下

1. 最基础的条件删除,如下所示

DELETE FROM table_name  where    table_name.name='dell'

还有一种按序删除的方式如下

DELETE FROM customers ORDER BY Name LIMIT 10

2.MySQL DELETE语句使用INNER JOIN子句

DELETE  a FROM tablename AS a LEFT JOIN temp_name AS b ON a.ID = b.ID WHERE b.UserID > 0;


DELETE  a FROM tablename AS a LEFT JOIN temp_name AS b ON a.ID = b.ID WHERE b.ID IS not null;

3.MySQL ON DELETE CASCADE示例

此时 有A和B两个表,当删除A表的记录时,B表关联的字段自动删除,此时需要用到这种方式;

第一步, 创建buildings表,如下创建语句:

USE testdb;
CREATE TABLE buildings (
    building_no INT PRIMARY KEY AUTO_INCREMENT,
    building_name VARCHAR(255) NOT NULL,
    address VARCHAR(255) NOT NULL
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

第二步, 创建rooms表,如下创建语句:

USE testdb;
CREATE TABLE rooms (
    room_no INT PRIMARY KEY AUTO_INCREMENT,
    room_name VARCHAR(255) NOT NULL,
    building_no INT NOT NULL,
    FOREIGN KEY (building_no)
        REFERENCES buildings (building_no)
        ON DELETE CASCADE
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

请注意,在外键约束定义的末尾添加ON DELETE CASCADE子句。

第三步插入部分数据

INSERT INTO buildings(building_name,address)
VALUES('海南大厦','海口市国兴大道1234号'),
      ('万达水城','海口市大同路1200号');

INSERT INTO rooms(room_name,building_no)
VALUES('Amazon',1),
      ('War Room',1),
      ('Office of CEO',1),
      ('Marketing',2),
      ('Showroom',2);

此时 删除building_no = 2 的记录,可以看到rooms表中也删除了

DELETE FROM buildings WHERE building_no = 2;

请注意,ON DELETE CASCADE仅支持使用存储引擎支持外键(如InnoDB)的表上工作。 某些表类型不支持诸如MyISAM的外键,因此应该在使用MySQL ON DELETE CASCADE引用操作的表上选择适当的存储引擎。

 类似资料: