sql - Adding a Foreign Key to an existing Table -
i forgot add column foreign key. tried doing following:
alter table gamestbl add console varchar(30) not null, index (console), foreign key(console) references consolestbl(consolename) on delete cascade on update cascade;
edit:
i tried adding field first , after constraint so:
alter table gamestbl add column console varchar(30); add constraint console foreign key (console) references consolestbl(consolename);
it seems want add missing column, index, , add foreign key constraint. afaik there isn't 1 single command all in 1 go. in smaller steps :)
also, note if games table has data in it, not able add not null
column without setting default.
here's 1 way this, viz adding missing column null
able, setting data, , changing not null
:
(i'm assuming mysql)
alter table gamestbl add console varchar(30) null; alter table gamestbl add foreign key(console) references consolestbl(consolename) on delete cascade on update cascade; create index ix1_gamesconsole on gamestbl(console); update gamestbl set console = 'playstation'; alter table gamestbl change column console console varchar(30) not null;
Comments
Post a Comment