实验:
//创建父表,并添加索引
CREATE TABLE parent(id INT,msg VARCHAR(200), INDEX index_id(id));
//查看索引
SHOW INDEX FROM parent;
//创建子表(外键)
CREATE TABLE child (c_id INT,c_mgs VARCHAR(200),FOREIGN KEY (c_id) REFERENCES parent (id)
ON DELETE CASCADE ON UPDATE CASCADE );
//插入数据
INSERT INTO parent VALUES (1,'aaa');
INSERT INTO child VALUES (1,'aaa');
------注意:如果子表外键参照的主表没有数据,子表插入数据将会报错
INSERT INTO child VALUES (2,'aaa');
错误代码: 1452
Cannot add or update a child row: a foreign key constraint fails (`czb`.`child`, CONSTRAINT `child_ibfk_1` FOREIGN KEY (`c_id`) REFERENCES `parent` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)
//查看插入数据
SELECT * FROM parent;
SELECT * FROM child;
//查看外键约束
SELECT * FROM information_schema.`KEY_COLUMN_USAGE` WHERE table_name='child';
SELECT * FROM information_schema.`REFERENTIAL_CONSTRAINTS`;
//删除外键约束
ALTER TABLE child DROP FOREIGN KEY child_ibfk_1;
//添加外键约束
ALTER TABLE child ADD FOREIGN KEY (c_id) REFERENCES parent (id)
ON DELETE CASCADE ON UPDATE CASCADE
ALTER TABLE child ADD FOREIGN KEY (c_id) REFERENCES parent (id)
ON DELETE CASCADE ON UPDATE CASCADE
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/30345407/viewspace-2096218/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/30345407/viewspace-2096218/