【问题标题】:Adding a foreign key to a table向表中添加外键
【发布时间】:2016-10-03 17:39:57
【问题描述】:

好久没练SQL了,忘记怎么给表加外键了

    mysql> alter table students 
add foreign key fk_unit(unitid) 
references unit(unitid) 
on delete no action 
on update cascade;
    ERROR 1072 (42000): Key column 'unitid' doesn't exist in table

我想知道为什么会这样?我的单元表有一个名为 unitid 的主键,为什么会一直这样?

【问题讨论】:

  • 您在学生表中具有相同名称的 unitid 列检查它。我认为这是不同的,这就是给出错误的原因。
  • 您的单元表有一个列 unitid,但可能是您的学生表没有列名 unitid。这就是错误所暗示的。

标签: mysql sql god


【解决方案1】:

试试这个应该可以的....

ALTER TABLE students 
ADD CONSTRAINT FK_UnitId FOREIGN KEY (unitid)
    REFERENCES  unit(unitid);

【讨论】:

    【解决方案2】:

    试试这个

    ALTER TABLE Students
    ADD FOREIGN KEY (unitid)
    REFERENCES unit(unitid)
    

    【讨论】:

      【解决方案3】:

      您的查询是正确的。 'students' 表中似乎缺少字段 'unitid' 或名称不同。

      【讨论】:

        猜你喜欢
        • 2019-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-22
        相关资源
        最近更新 更多