这段代码为何外键加不上去内容:根据提供的代码,有一些问题会导致外键无法添加到表中。

  1. 外键约束的参照表应该是被引用的表,而不是引用其他表的表。在cy_user表中,constraint cy_uc foreign key (user_id) references cy_class(class_id) 这一行试图将cy_useruser_id列作为外键引用cy_classclass_id列,但是实际上应该将cy_classclass_id列作为外键引用cy_useruser_id列。因此,应该调整外键约束的顺序。

  2. 数据类型不匹配。在cy_user表中,user_id列的数据类型为int(10),而在cy_class表中,class_id列的数据类型也是int(10)。在添加外键约束时,两个列的数据类型必须完全匹配。

以下是已进行修改的代码:

create table cy_class(
    id int(10) unsigned primary key auto_increment not null,
    class_id int(10) NOT NULL,
    name varchar(255) NOT NULL,
    teacher varchar(255) NOT NULL,
    email varchar(255) NOT NULL,
    constraint cy_uc foreign key (class_id) references cy_user(user_id)
) comment '班级表';

create table cy_user(
    id int(10) unsigned primary key auto_increment not null,
    user_id int(10) NOT NULL,
    name varchar(255) NOT NULL,
    age int(10) NOT NULL,
    phone varchar(255) NOT NULL,
    height int NOT NULL
) comment '用户表';

create table cy_commodity(
    id int(10) unsigned primary key auto_increment not null,
    commodity_id int(10) NOT NULL,
    name varchar(255) NOT NULL,
    qty int(10) NOT NULL,
    price int(10) NOT NULL,
    constraint cy_cu foreign key (commodity_id) references cy_user(user_id)
) comment '商品表';

在上述修改后的代码中,我们将外键约束放在了cy_class表的定义中,并将其指向cy_user表的user_id列。同时,修正了数据类型以确保两个表之间的外键匹配。请注意,外键约束应根据具体的业务逻辑进行调整,确保表之间的关联关系正确。

MySQL 外键约束添加失败:常见问题及解决方案

原文地址: https://www.cveoy.top/t/topic/bTU2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录