-- 创建测试主表. 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');
1> -- 创建外键(使用 ON DELETE CASCADE 选项,删除主表的时候,同时删除子表)
2> ALTER TABLE test_sub
3> ADD CONSTRAINT main_id_cons
4> FOREIGN KEY (main_id) REFERENCES test_main ON DELETE CASCADE;
5>
6> -- 测试删除主表数据. 将成功地执行.
7> DELETE
8> TEST_MAIN
9> WHERE
10> ID = 1;
11>
12> -- 测试检索子表,应该只有一条 main_id = 2 的数据.
13> SELECT
14> *
15> FROM
16> test_sub;
17>
18> go
(1 行受影响)
id main_id value
----------- ----------- ----------
2 2 TWOTWO
(1 行受影响)