将复合主键的一部分用作外键

发布于 2025-02-08 22:30:21 字数 930 浏览 0 评论 0原文

我正在使用PostgreSQL。

我有一个表帐户,其中account_id是主要键。我还有一个名为关系的表格,带有复合主键(follower_id,polust_id)。每个关系必须是唯一的。

ALTER TABLE accounts ADD CONSTRAINT users_pk PRIMARY KEY (account_id);
ALTER TABLE relations ADD CONSTRAINT relations_pk PRIMARY KEY (follower_id, following_id);

我想从follower_id(关系) - >创建一个外键约束。 account_id(帐户),以及以下_id。

ALTER TABLE relations ADD CONSTRAINT follower_id_fk FOREIGN KEY (follower_id) REFERENCES accounts (account_id) ON DELETE CASCADE

数据库不接受此外键。我收到以下错误:

错误:在表“关系”上插入或更新违反外键约束“ follower_id_fk” 详细信息:键(follower_id)=(4)在表“帐户”中不存在。

我理解这一点,因为它是复合主键。

我想实现的目标:

删除帐户时,我想删除account_id是follower_id的所有记录(delete cascade 上的)以及以下是以下_ID 。

我可以在NodeJS代码或触发功能中执行此操作,但是我不知道最佳性能是什么。有人知道/最好的解决方案吗?

I'm using PostgreSQL.

I have a table accounts with account_id as the primary key. I also have a second table called relations with a composite primary key (follower_id, following_id). Each relation must be unique.

ALTER TABLE accounts ADD CONSTRAINT users_pk PRIMARY KEY (account_id);
ALTER TABLE relations ADD CONSTRAINT relations_pk PRIMARY KEY (follower_id, following_id);

I want to create a foreign key constraint from follower_id (relations) -> account_id (accounts), and the same with following_id.

ALTER TABLE relations ADD CONSTRAINT follower_id_fk FOREIGN KEY (follower_id) REFERENCES accounts (account_id) ON DELETE CASCADE

This foreign key is not accepted by the database. I get the following error:

ERROR: insert or update on table "relations" violates foreign key constraint "follower_id_fk"
DETAIL: Key (follower_id)=(4) is not present in table "accounts".

I understand this, because it's a composite primary key.

What I want to achieve:

When an account is deleted, I want to delete all the records where the account_id is the follower_id (ON DELETE CASCADE) AND where it is the following_id.

I could do this in my nodejs code or with a trigger function, but I don't know what will be the best performance-wise. Does anyone knows a/the best solution?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文