我就不造你的 学生表和成绩表了.
用 test_main 表 和 test_sub 代替说明
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
-- 创建测试主表. 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 外键约束的处理机制来处理
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
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)
|
如果你非要使用触发器来处理, 那么下面是一个例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
-- 创建测试主表. 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)
|