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

从零构建数据模型:PostgreSQL添加外键报错求助

问题解决:PostgreSQL外键创建报错"relation does not exist"

报错原因

你创建表时使用了带引号的标识符(如 "SendingCountries"、"Years"),PostgreSQL 会严格保留这些名称的大小写格式。但执行外键添加语句时,ALTER TABLE SendingCountries 未加引号,PostgreSQL 会自动将表名转换为全小写的 sendingcountries,与你实际创建的大小写混合表名不匹配,因此数据库找不到对应的表。

修正后的外键添加语句

给表名和字段名加上引号,完全匹配创建时的大小写:

ALTER TABLE public."SendingCountries"
ADD CONSTRAINT FK_SendingCountries_Years
FOREIGN KEY ("Year2Years")
REFERENCES public."Years"("ID_Year");

避免后续问题的建议

如果不想纠结大小写问题,建议创建表时使用全小写、不带引号的标识符,PostgreSQL 会自动兼容大小写操作:

CREATE TABLE IF NOT EXISTS public.years
(
    id_year integer,
    year integer,
    PRIMARY KEY (id_year)
);

CREATE TABLE IF NOT EXISTS public.sending_countries
(
    id_send_country integer,
    year2years integer,
    country2countries integer,
    female_legis2female_legislators integer,
    feminist_policy boolean,
    PRIMARY KEY (id_send_country)
);

此时添加外键无需关注大小写:

ALTER TABLE sending_countries
ADD CONSTRAINT fk_sending_countries_years
FOREIGN KEY (year2years)
REFERENCES years(id_year);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 17:37:02