mysql 使用foreign key(外來鍵)

abin1703發表於2016-05-09


實驗:

//建立父表,並新增索引
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 

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/30345407/viewspace-2096218/,如需轉載,請註明出處,否則將追究法律責任。

相關文章