Mega Code Archive

 
Categories / MySQL / Table Index
 

Alter table to add foreign key

mysql> mysql> CREATE TABLE T1     ->       (A INTEGER NOT NULL PRIMARY KEY,     ->        B INTEGER NOT NULL); Query OK, 0 rows affected (0.00 sec) mysql> mysql> mysql> CREATE TABLE T2     ->       (A INTEGER NOT NULL PRIMARY KEY,     ->        B INTEGER NOT NULL,     ->        CONSTRAINT C1 CHECK (B > 0),     ->        CONSTRAINT FK1 FOREIGN KEY (A) REFERENCES T1 (A)); Query OK, 0 rows affected (0.00 sec) mysql> mysql> ALTER TABLE T1     ->    ADD CONSTRAINT FK2 FOREIGN KEY (A) REFERENCES T2 (A); Query OK, 0 rows affected (0.01 sec) Records: 0  Duplicates: 0  Warnings: 0 mysql> mysql> mysql> drop table t1; ERROR 1217 (23000): Cannot delete or update a parent row: a foreign key constraint fails mysql> drop table t2; ERROR 1217 (23000): Cannot delete or update a parent row: a foreign key constraint fails