重庆分公司,新征程启航
为企业提供网站建设、域名注册、服务器等服务
delete t.*,t1.*,t2.* from tale_a t1, tale_a_b t, tale_b t2
创新互联建站-专业网站定制、快速模板网站建设、高性价比宾阳网站开发、企业建站全套包干低至880元,成熟完善的模板库,直接使用。一站式宾阳网站制作公司更省心,省钱,快速模板网站建设找我们,业务覆盖宾阳地区。费用合理售后完善,10年实体公司更值得信赖。
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 替换成你的三个表的关联条件
我就不造你的 学生表和成绩表了.
用 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)
这个在建表的时候就可以指定了
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的记录都会被删掉。