简体   繁体   English

SQL,通过1条语句中的ALTER TABLE添加作为外键的列

[英]SQL, add column which is a foreign key via ALTER TABLE in 1 Statement

i want to extend a already created table by a column, but the column is a foreign key. 我想通过列扩展已经创建的表,但是该列是外键。 This has to happen in 1 SQL statement. 这必须在1条SQL语句中进行。 I know than i can use the ALTER TABLE operation to achieve it, but there is a small error message. 我知道我可以使用ALTER TABLE操作来实现它,但是有一条很小的错误消息。

Existing Table: 现有表:

//relation, because table already exists
Relation(A, B, C, D, E, F)

//creating a table F //创建表F

CREATE TABLE `MyTable`(
`PK` INT(11) NOT NULL,
`H` VARCHAR(30) NOT NULL,
`I` INT NOT NULL,
PRIMARY KEY(`PK`),
FOREIGN KEY(`I`) REFERENCES `IT`(`I`)
);

Attempt to add the column I which is a foreign key(everything in one statement): 尝试添加作为外键的列I(一个语句中的所有内容):

ALTER TABLE `R`
ADD COLUMN `PK` INT(11) NOT NULL,
ADD CONSTRAINT FOREIGN KEY (`PK`) REFERENCES `MyTable`(`PK`);

Error Message: 错误信息:

Cannot add or update a child row: a foreign key constraint fails.

Important: I know there could be a problem if the IT table has entries, but in our case, the table is empty. 重要说明:我知道如果IT表具有条目,则可能会出现问题,但是在我们的情况下,该表为空。

Any suggestions? 有什么建议么?

EDIT: SOLUTION: Removed the constrain "NOT NULL". 编辑:解决方案:删除了约束“ NOT NULL”。 Thanks @Milan Švec 谢谢@米兰Švec

-------------------------------------------

CREATE TABLE `MyTable`(
`PK` INT(11),
`H` VARCHAR(30) NOT NULL,
`I` INT NOT NULL,
PRIMARY KEY(`PK`),
FOREIGN KEY(`I`) REFERENCES `IT`(`I`)
);


ALTER TABLE `R`
ADD COLUMN `PK` INT(11),
ADD CONSTRAINT FOREIGN KEY (`PK`) REFERENCES `MyTable`(`PK`);

--------------------------------------

Not sure, but try to make the column nullable first. 不确定,但请尝试首先使该列可为空。 Change it to not nullable later, after filling by real values. 在填充实数值后,将其更改为不可为空。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM