【问题标题】:mysql error 1822 when trying to create new table with a FOREIGN KEYmysql 在尝试使用 FOREIGN KEY 创建新表时出现错误 1822
【发布时间】:2023-03-12 04:45:02
【问题描述】:

尝试以下代码:

create table donation(
    donation_number int not null primary key  ,
    product_id int not null
);

create table stock ( 
    product_id int not null primary key, 
    available_qty int not null, 
    FOREIGN KEY (product_id ) REFERENCES donation(product_id)
);

回馈

错误代码:1822。添加外键约束失败。引用表“捐赠”中缺少约束“stock_ibfk_1”的索引。

为什么?我该如何解决这个问题?

【问题讨论】:

标签: mysql sql foreign-keys


【解决方案1】:

要创建外键关系,要创建关系的父表列必须是唯一的或主要的,并且它们也必须具有相同的数据类型和大小

捐赠表中的product_id 不是唯一的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多