MySQL ALTER TABLE 添加约束

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10193153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 12:59:35  来源:igfitidea点击:

ALTER TABLE add constraint

mysqlsqldatabasephpmyadmin

提问by ABLX

CREATE TABLE Properties
(
    ID int AUTO_INCREMENT,
    language int,
    stonecolor int,
    gamefield int,
    UserID int,
    PRIMARY KEY(ID),
    FOREIGN KEY(language) REFERENCES Language(ID),
    FOREIGN KEY(stonecolor) REFERENCES StoneColor(ID),
    FOREIGN KEY(gamefield) REFERENCES GameField(ID)
) ENGINE = INNODB;

CREATE TABLE User
(
    ID int AUTO_INCREMENT,
    vorname varchar(30) NOT NULL,
    name varchar(30) NOT NULL,
    email varchar(40) NOT NULL,
    password varchar(40) NOT NULL,
    nickname varchar(15) NOT NULL,
    score int,
    isadmin int DEFAULT 0,
    gamesPlayed int,
    properties int NOT NULL,
    PRIMARY KEY(ID),
    UNIQUE (email),
    UNIQUE (nickname)

) ENGINE = INNODB;

ALTER TABLE User 
(
    ADD CONSTRAINT userPropertie
    FOREIGN KEY(properties)
    REFERENCES Properties(ID)
)

The tables were created properly, but the ALTER TABLE doesn't work. cant figure out why?

表已正确创建,但 ALTER TABLE 不起作用。不知道为什么?

I used this as reference http://www.w3schools.com/sql/sql_foreignkey.asp

我用这个作为参考http://www.w3schools.com/sql/sql_foreignkey.asp

Error 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '( ADD CONSTRAINT userPropertie FOREIGN KEY(properties) REFERENCES Properties(' at line 2

错误 1064 - 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以获取在“( ADD CONSTRAINT userPropertie FOREIGN KEY(properties) REFERENCES Properties(' at line 2

回答by Andomar

Omit the parenthesis:

省略括号:

ALTER TABLE User 
    ADD CONSTRAINT userProperties
    FOREIGN KEY(properties)
    REFERENCES Properties(ID)

回答by Vladimir Salguero

ALTER TABLE `User`
ADD CONSTRAINT `user_properties_foreign`
FOREIGN KEY (`properties`)
REFERENCES `Properties` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;