指向主键的外键也是唯一键的一部分

时间:2021-01-19 17:15:55

标签: sql phpmyadmin mariadb dbeaver

我使用 MariaDb 创建了一个数据库。我有以下 author 表(以 id 作为主键),该表由另外两个表 author_personalauthor_corporate 扩展,代表两种不同类型的作者并具有不同的领域:

CREATE TABLE `author` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `author_type` char(1) NOT NULL,
  -- other fields
  PRIMARY KEY (`id`),
  UNIQUE KEY `author_UN` (`id`,`author_type`) USING BTREE,
  CONSTRAINT `author_CHECK_type` CHECK (`author_type` in ('P','C'))
);

CREATE TABLE `author_personal` (
  `id` int(10) unsigned NOT NULL,
  `surname` varchar(30) DEFAULT NULL,
  `name` varchar(30) DEFAULT NULL,
  -- other fields
  `author_type` char(1) GENERATED ALWAYS AS ('P') VIRTUAL,
  PRIMARY KEY (`id`),
  KEY `author_personal_FK` (`id`,`author_type`),
  CONSTRAINT `author_personal_FK` FOREIGN KEY (`id`, `author_type`) REFERENCES `author` (`id`, `author_type`) ON DELETE CASCADE
);

CREATE TABLE `author_corporate` (
  `id` int(10) unsigned NOT NULL,
  `corporate_name` varchar(50) DEFAULT NULL,
  `corporate_acronym` varchar(5) DEFAULT NULL,
  `author_type` char(1) GENERATED ALWAYS AS ('C') VIRTUAL,
  PRIMARY KEY (`id`),
  KEY `author_corporate_FK` (`id`,`author_type`),
  CONSTRAINT `author_corporate_FK` FOREIGN KEY (`id`, `author_type`) REFERENCES `author` (`id`, `author_type`) ON DELETE CASCADE
);

虽然 author.id 就足够了,我还是决定创建一个 UNIQUE KEY (id, author_type) 由其他两个表中的外键引用,这样它就可以不可能从 author_personal 引用未标记为 P 的 author,以及从 author_corporate 引用未标记为 C 的 author

当我想使用主键引用 author 时,问题就出现了,如下表所示:

CREATE TABLE `work_authors` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `work_id` int(10) unsigned NOT NULL,
  `author_id` int(10) unsigned NOT NULL,
  -- other fields
  PRIMARY KEY (`id`),
  KEY `work_authors_FK` (`work_id`),
  KEY `work_authors_FK_author` (`author_id`) USING BTREE,
  CONSTRAINT `work_authors_FK` FOREIGN KEY (`work_id`) REFERENCES `work` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `work_authors_FK_author` FOREIGN KEY (`author_id`) REFERENCES `author` (`id`) ON UPDATE CASCADE
);
    

DBeaver 和 PhpMyAdmin 都认为 work_authors_FK_author 引用了 author_UN 而不是实际的主键 (author.id)。

DBeaver Foreign Key description

这意味着我无法点击 work_authors.author_id 中的值并打开 authors 中的引用记录,因为我收到以下错误:

Entity [davide_library.author] association [work_authors_FK_author] columns differs from referenced constraint [author_UN] (1<>2)

我使用 DBeaver 创建了外键。尽管我选择了 PRIMARY 作为唯一键,但在外键列表中,它始终将 author_UN 显示为引用对象。我不知道这种行为是否取决于 MariaDB 或 DBeaver。

我的问题是:

有没有办法在 DDL 中显式引用主键而不是唯一键?

或者:

除了 UNUQUE 约束之外,是否还有其他方法可以检查 author_personal 是否仅引用标有 P 的作者,而 author_corporate 也是如此?

0 个答案:

没有答案
相关问题