You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MySQL添加外键约束失败:Error 3780问题求助

错误原因排查与修复

核心错误:外键字段类型不兼容

错误提示里的category属于SQL解析时的误报,实际触发问题的是字段类型不匹配:

  • Category表的category_id是serial类型(在PostgreSQL中等价于integer+自增序列)
  • Product表中对应的外键字段category_id被定义为bigint
    两种类型无法匹配,直接导致外键约束创建失败。

其他连带错误

代码里还有几个必须修复的问题:

  • Provider表主键字段拼写错误:写成了privider_id(多了一个字母i),但Product表外键引用的是provider_id,会触发第二个外键约束报错。
  • 无效注释:Product表中的#constraint 'provider_for_product'是无效SQL注释,SQL中应使用--或/* */格式。
  • 校验约束用法错误:sounds like是用于语音相似度匹配的语法,不能用来做正则格式校验,需根据数据库类型改用正则匹配(MySQL用REGEXP,PostgreSQL用~)。

修复后的完整代码

drop table if exists Provider;
drop table if exists Category;
drop table if exists Product;

create table Provider
 (
 provider_id serial not null primary key, 
 login_password varchar(20) not null
        constraint passrule3 check(login_password ~ '[A-Za-z0-9]{6,20}'),
 fathersname varchar(20) not null,
 name_of_contact_face varchar(10) not null,
 surname varchar(15), 
 e_mail varchar(25) unique
        constraint emailrule2 check(e_mail ~ '[A-Za-z0-9]{10}@gmail.com')
 );
 
create table Category
(
title varchar(20),
category_id serial not null primary key
);

create table Product
(
 barecode serial not null primary key, 
 provider_id int not null, 
 manufacturer varchar(25) not null, 
 category_id int not null, 
 dimensions varchar(10) not null, 
 amount int not null,
 date_of_registration timestamp not null,
-- constraint provider_for_product
 foreign key (provider_id) references Provider (provider_id) on delete restrict on update cascade,
 foreign key (category_id) references Category (category_id) on delete restrict on update cascade
);

修复说明

  1. 将Product表的provider_id和category_id类型改为int,与主表的serial(对应int)匹配。
  2. 修正Provider表主键字段的拼写错误为provider_id。
  3. 将无效注释改为SQL标准注释格式--。
  4. 把check约束里的sounds like替换为PostgreSQL的正则匹配符~,同时修正正则表达式的语法错误(去掉多余的括号和转义符)。
  5. 将datetime改为PostgreSQL支持的timestamp类型(如果使用MySQL则保留datetime)。

内容的提问来源于stack exchange,提问作者Serhii

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 10:50:37