mysql怎么级联删除 数据库的级联删除
MySQL写触发器,级联删除
我就不造你的 学生表和成绩表了.
成都创新互联公司是一家专业提供广陵企业网站建设,专注与成都网站设计、网站制作、外贸营销网站建设、H5页面制作、小程序制作等业务。10年已为广陵众多企业、政府机构等服务。创新互联专业网站制作公司优惠进行中。
用 test_main 表 和 test_sub 代替说明
-- 创建测试主表. ID 是主键.
CREATE TABLE test_main (
id INT NOT NULL,
value VARCHAR(10),
PRIMARY KEY(id)
);
-- 创建测试子表.
CREATE TABLE test_sub (
id INT NOT NULL,
main_id INT ,
value VARCHAR(10),
PRIMARY KEY(id)
);
-- 插入测试主表数据.
INSERT INTO test_main(id, value) VALUES (1, 'ONE');
INSERT INTO test_main(id, value) VALUES (2, 'TWO');
-- 插入测试子表数据.
INSERT INTO test_sub(id, main_id, value) VALUES (1, 1, 'ONEONE');
INSERT INTO test_sub(id, main_id, value) VALUES (2, 2, 'TWOTWO');
通过 DELETE CASCADE 外键约束的处理机制来处理
mysql ALTER TABLE test_sub
- ADD CONSTRAINT main_id_cons
- FOREIGN KEY (main_id)
- REFERENCES test_main(id)
- ON DELETE CASCADE//
Query OK, 2 rows affected (0.16 sec)
Records: 2 Duplicates: 0 Warnings: 0
mysql DELETE FROM
- test_main
- WHERE
- id = 1;
- //
Query OK, 1 row affected (0.02 sec)
mysql SELECT
- *
- FROM
- test_sub;
- //
+----+---------+--------+
| id | main_id | value |
+----+---------+--------+
| 2 | 2 | TWOTWO |
+----+---------+--------+
1 row in set (0.00 sec)
如果你非要使用触发器来处理, 那么下面是一个例子:
-- 创建测试主表. ID 是主键.
CREATE TABLE t_test_main (
id INT NOT NULL,
value VARCHAR(10),
PRIMARY KEY(id)
);
-- 创建测试子表.
CREATE TABLE t_test_sub (
id INT NOT NULL,
main_id INT ,
value VARCHAR(10),
PRIMARY KEY(id)
);
-- 插入测试主表数据.
INSERT INTO t_test_main(id, value) VALUES (1, 'ONE');
INSERT INTO t_test_main(id, value) VALUES (2, 'TWO');
-- 插入测试子表数据.
INSERT INTO t_test_sub(id, main_id, value) VALUES (1, 1, 'ONEONE');
INSERT INTO t_test_sub(id, main_id, value) VALUES (2, 2, 'TWOTWO');
DELIMITER //
CREATE TRIGGER tr_t_test_main_Del
BEFORE DELETE ON t_test_main
FOR EACH ROW
BEGIN
DELETE FROM t_test_sub WHERE main_id = OLD.id;
END;
//
DELIMITER ;
mysql delete from t_test_main where id = 1;
Query OK, 1 row affected (0.01 sec)
mysql select * from t_test_sub;
+----+---------+--------+
| id | main_id | value |
+----+---------+--------+
| 2 | 2 | TWOTWO |
+----+---------+--------+
1 row in set (0.00 sec)
mysql怎么实现多对多级联删除
delete t.*,t1.*,t2.* from tale_a t1, tale_a_b t, tale_b t2
where t1.id=t.aid and t.bid=t2.id and t1.你的删除条件
前提是 a表 a_b 表 b表 根据你的关联条件 inner join 能够查到内容
才会删除成功
t1.id=t.aid and t.bid=t2.id 替换成你的三个表的关联条件
mysql怎么设置级联删除
这个在建表的时候就可以指定了
CREATE TABLE buildings (
building_no INT PRIMARY KEY AUTO_INCREMENT,
building_name VARCHAR(255) NOT NULL,
address VARCHAR(255) NOT NULL
);
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
);
当执行
DELETE FROM buildings
WHERE
building_no = 2;的时候,rooms表中的building_no =2的记录都会被删掉。
当前题目:mysql怎么级联删除 数据库的级联删除
当前地址:http://scyanting.com/article/dopsioi.html