[英]Adding a Foreign Key to an existing Table
I forgot to add a column which is a foreign key. 我忘了添加一个外键列。 I tried doing the 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 the field first and after that the constraint like so: 我尝试先添加字段,然后再添加如下约束:
ALTER TABLE GamesTbl
ADD Column Console varchar(30);
ADD CONSTRAINT Console FOREIGN KEY (Console)
REFERENCES ConsolesTbl(ConsoleName);
It seems you want to add the missing column, an index, and also add a foreign key constraint. 似乎您想添加缺少的列,索引,并添加外键约束。 AFAIK there isn't one single command to do all this all in one go.
AFAIK没有一个命令可以一次性完成所有这些操作。 I would do this in smaller steps :)
我会在较小的步骤中执行此操作:)
Also, note that if the Games Table already has data in it, you will not be able to add a NOT NULL
column to it without also setting a default. 另外,请注意,如果“游戏表”中已经有数据,则在未设置默认值的情况下将无法向其添加“
NOT NULL
列。
Here's one way to do this, viz by adding the missing column as NULL
able, setting data, and then changing it to NOT NULL
: 这是执行此操作的一种方法,即通过将缺少的列添加为
NULL
能力,设置数据,然后将其更改为NOT NULL
:
(I'm also assuming MySql) (我也假设是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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.