Friday, 16 October 2015

Add column with foreign key in mysql

Add only a constraint on a column

ALTER TABLE `SCHEMANAME`.`TABLE1` 
ADD CONSTRAINT `FK_TABLE2_COLUMN` FOREIGN KEY (`FK_COLUMN`)  
REFERENCES `SCHEMANAME`.`TABLE2`(`PK_COLUMN`);
 

Adding a column with constraint

ALTER TABLE `SCHEMANAME`.`TABLE1` 
ADD COLUMN `FK_COLUMN` BIGINT(20) NOT NULL, 
ADD CONSTRAINT `FK_TABLE2_COLUMN` FOREIGN KEY (`FK_COLUMN`) 
REFERENCES `SCHEMANAME`.`TABLE2`(`PK_COLUMN`);