3个回答
2013-06-26
展开全部
我就不造你的 学生表和成绩表了.
用 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)
展开全部
不需要触发器,在sc表上创建关联student主键的级联删除外键
更多追问追答
追问
怎么创建
追答
思路给你了,不能简单的拿来主义,为什么不学习一下主键、外键,增加点知识呢?
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
create or replace trigger del_table
after delete on student
for each row
begin
delect from sc;
end del_table;
after delete on student
for each row
begin
delect from sc;
end del_table;
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询