Wednesday, June 4, 2014

How to add Foreign Key to existing table column in mysql?

It is simple to add a foreign key to a column in Existing table.The Following command adds foreign key to the table


alter table table_name add CONSTRAINT foreign_key_constraint_name FOREIGN KEY (column_name)  REFERENCES reference_table_name (reference_table_column_name) ON UPDATE CASCADE ON DELETE CASCADE;  
                       
Eg:    
alter table MerchantOfferImage add CONSTRAINT banner_image_id_fk FOREIGN KEY (banner_image_id)  REFERENCES MerchantOffer (offer_id) ON UPDATE CASCADE ON DELETE CASCADE;
                                                                   or
alter table MerchantOfferImage add foreign key(offer_id) references MerchantOffer (offer_id)  ON UPDATE CASCADE ON DELETE CASCADE;

0 comments:

Post a Comment