gpt4 book ai didi

非唯一键的 Mysql 外键——这怎么可能?

转载 作者:可可西里 更新时间:2023-11-01 06:37:04 25 4
gpt4 key购买 nike

我在将 mysql 数据库迁移到 postgres 时无意中发现了 DDL 中的以下 block (注意:这是我从 mysqldump 得到的):

CREATE TABLE `catalog_property_value` (
`id` int(10) unsigned NOT NULL,
`property_id` int(10) unsigned NOT NULL,
`sort` int(10) unsigned NOT NULL,
`value_number` decimal(15,5) DEFAULT NULL,
`value_string` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`,`sort`),
KEY `FK_catalog_property_value` (`property_id`),
KEY `NewIndex1` (`id`),
CONSTRAINT `FK_catalog_property_value` FOREIGN KEY (`property_id`) REFERENCES `catalog_property` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
SET character_set_client = @saved_cs_client;

CREATE TABLE `catalog_realty_property_value_link` (
`realty_id` int(10) unsigned NOT NULL,
`property_id` int(10) unsigned NOT NULL,
`value_id` int(10) unsigned NOT NULL,
`dt_is_denormalized` tinyint(1) unsigned NOT NULL,
PRIMARY KEY (`realty_id`,`property_id`,`value_id`),
KEY `FK_catalog_realty_property_value_link_property` (`property_id`),
KEY `FK_catalog_realty_property_value_link_value` (`value_id`),
CONSTRAINT `FK_catalog_realty_property_value_link_property` FOREIGN KEY (`property_id`) REFERENCES `catalog_property` (`id`) ON DELETE CASCADE,
CONSTRAINT `FK_catalog_realty_property_value_link_realty` FOREIGN KEY (`realty_id`) REFERENCES `catalog_realty` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `FK_catalog_realty_property_value_link_value` FOREIGN KEY (`value_id`) REFERENCES `catalog_property_value` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

现在,我在这里看到的是第一个表中唯一的唯一键是 (id, sort) 的组合:

PRIMARY KEY (`id`,`sort`),

但是,第二个表仅通过 id 列引用了第一个表,这不是唯一的!

CONSTRAINT `FK_catalog_realty_property_value_link_value` FOREIGN KEY (`value_id`) REFERENCES `catalog_property_value` (`id`) ON DELETE CASCADE

那么,我在这里做错了什么?这怎么可能?

最佳答案

来自手册:

Deviation from SQL standards: A FOREIGN KEY constraint that references a non-UNIQUE key is not standard SQL. It is an InnoDB extension to standard SQL.

所以看起来 InnoDB 允许非唯一索引作为外键引用的候选者。手册在其他地方指出,您可以在引用的索引中引用列的子集,只要引用的列首先列出并且顺序与主键相同。

因此,这个定义在 InnoDB 中是合法的,尽管它不是标准的 SQL,至少让我对最初设计者的意图有点困惑。

Manual page here .

关于非唯一键的 Mysql 外键——这怎么可能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2362163/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com