【问题标题】:join table referencing non unique foreign key连接表引用非唯一外键
【发布时间】:2019-01-21 18:47:45
【问题描述】:

我在数据库中有以下表格。 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),
);

允许此功能的最佳做法是什么?

【问题讨论】:

  • 为什么phrases 表中允许重复?

标签: sql database postgresql schema


【解决方案1】:

修改短语表,为外键关系提供唯一键。也许:

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)
);

满足你的条件:

  1. 每个phrase 都在phrases 表中,因为not null 和外键引用。
  2. 每个不同的短语在此表中最多出现一次。这是因为 phrase 的唯一约束。

每个短语恰好出现一次需要填充表格。然后,您需要在表上使用触发器,以确保在创建新短语时插入一行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-09
    • 1970-01-01
    • 2012-10-25
    • 2019-02-27
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多