[英]join table referencing non unique foreign key
我在数据库中有以下表格。 phrases
允许存储重复的短语。
CREATE TABLE phrases (
id INTEGER PRIMARY KEY,
phrase VARCHAR(1000),
creation_date TIMESTAMP WITH TIME ZONE NOT NULL,
);
CREATE TABLE intents (
id INTEGER PRIMARY KEY,
name VARCHAR(10) UNIQUE
);
我想在短语和意图之间创建一个联接表。 我要强制执行:
由于phrases
的外键不是唯一的,因此以下操作失败。
CREATE TABLE phrases_intents (
phrase VARCHAR(1000) REFERENCES phrases (phrase),
intent VARCHAR(10) REFERENCES intents (name),
PRIMARY KEY (phrase),
);
允许此功能的最佳实践是什么?
修改短语表以具有用于外键关系的唯一键。 也许:
CREATE TABLE phrases (
id INTEGER PRIMARY KEY,
phrase VARCHAR(1000),
creation_date TIMESTAMP WITH TIME ZONE NOT NULL,
unique (phrase, id)
);
然后在phrase_intents
使用此键:
CREATE TABLE phrase_intents (
phrase_intents_id serial primary key,
phrase varchar(1000) not null,
phrase_id int not null,
intent_id int references intents (id),
foreign key (phrase, phrase_id) references phrases(phrase, id),
unique (phrase)
);
您的条件得到满足:
phrase
都在phrases
表中,因为它not null
和外键引用。 phrase
的唯一约束。 对于每一个短语准确出现一次需要填充表。 然后,您将需要在表上使用触发器,以确保在创建新短语时会插入一行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.