【问题标题】:ALTER TABLE add constraintALTER TABLE 添加约束
【发布时间】:2012-04-28 21:44:48
【问题描述】:

用户和属性表已正确创建

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 不起作用。

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

不知道为什么?

我以此为参考http://www.w3schools.com/sql/sql_foreignkey.asp

错误 1064 - 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以获取在 '( 添加约束用户属性 外键(属性) REFERENCES 属性('在第 2 行

【问题讨论】:

标签: mysql sql ddl alter-table


【解决方案1】:

省略括号:

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

【讨论】:

    【解决方案2】:
    ALTER TABLE `User`
    ADD CONSTRAINT `user_properties_foreign`
    FOREIGN KEY (`properties`)
    REFERENCES `Properties` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION;
    

    【讨论】:

      【解决方案3】:
      alter table User 
          add constraint userProperties
          foreign key (properties)
          references Properties(ID)
      

      【讨论】:

      • 请尝试添加此代码如何解决问题的说明
      猜你喜欢
      • 1970-01-01
      • 2022-01-25
      • 1970-01-01
      • 2021-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-17
      相关资源
      最近更新 更多