gpt4 book ai didi

mysql - 具有复合主键的外键

转载 作者:行者123 更新时间:2023-11-29 05:28:33 25 4
gpt4 key购买 nike

一个表有一个列引用另一个表列,该列是复合主键。我该如何编写查询?它显示此错误。我该如何解决。

错误 1050:无法创建表“recdesk.#sql-5e8_33”(错误号:150)

SQL语句:

ALTER TABLE `recdesk`.`facility`
CHANGE COLUMN `organization_id` `organization_id` INT(11) NOT NULL DEFAULT 0,
CHANGE COLUMN `facility_id` `facility_id` INT(11) NOT NULL DEFAULT 0,

ADD CONSTRAINT `fk_organization_id`
FOREIGN KEY (`organization_id` )
REFERENCES `recdesk`.`facility_type` (`organization_id` )
ON DELETE RESTRICT
ON UPDATE RESTRICT,

ADD CONSTRAINT `fk_facility_type_id`
FOREIGN KEY (`facility_type_id` )
REFERENCES `recdesk`.`facility_type` (`facility_type_id` )
ON DELETE RESTRICT
ON UPDATE RESTRICT

, ADD INDEX `fk_organization_id_idx` (`organization_id` ASC)
, ADD INDEX `fk_facility_type_id_idx` (`facility_type_id` ASC)


ERROR: Error when running failback script. Details follow.

ERROR 1050: Table 'facility' already exists

SQL Statement:

CREATE TABLE `facility` (
`organization_id` int(11) NOT NULL,
`facility_id` int(11) NOT NULL,
`name` varchar(50) DEFAULT NULL,
`address_line1` varchar(50) DEFAULT NULL,
`address_line2` varchar(50) DEFAULT NULL,
`city` varchar(30) DEFAULT NULL,
`state` varchar(2) DEFAULT NULL,
`zip_code` varchar(9) DEFAULT NULL,
`description` varchar(1000) DEFAULT NULL,
`note` varchar(250) DEFAULT NULL,
`capacity` smallint(6) DEFAULT NULL,
`show_on_portal` char(1) DEFAULT NULL,
`active_indicator` char(1) DEFAULT NULL,
`primary_facility_indicator` char(1) DEFAULT NULL,
`facility_type_id` int(11) DEFAULT NULL,
`parent_facility_id` int(11) DEFAULT NULL,
`create_date` datetime DEFAULT NULL,
`show_schedule_on_portal` char(1) DEFAULT NULL,
`show_usage_on_portal` char(1) DEFAULT NULL,
`enable_online_reservation` char(1) DEFAULT NULL,
`gl_code_id` int(11) DEFAULT NULL,
`gl_code_deposit_id` int(11) DEFAULT NULL,

PRIMARY KEY (`organization_id`,`facility_id`)

) ENGINE=InnoDB DEFAULT CHARSET=latin1

最佳答案

如果 Facility 表中的 (Organization_ID, Facility_ID) 列对是对 (Organization_ID, Facility_ID) 列的外键引用 在表 Facility_Type 中,这是 Facility_Type 中的唯一键,那么您需要创建一个外键约束:

ALTER TABLE `recdesk`.`facility`
CHANGE COLUMN `organization_id` `organization_id` INT(11) NOT NULL DEFAULT 0,
CHANGE COLUMN `facility_id` `facility_id` INT(11) NOT NULL DEFAULT 0,

ADD CONSTRAINT `fk_facility_type`
FOREIGN KEY (`organization_id`, `facility_type`)
REFERENCES `recdesk`.`facility_type` (`organization_id`, `facility_type`)
ON DELETE RESTRICT
ON UPDATE RESTRICT,

ADD INDEX `fk_facility_type_idx` (`organization_id` ASC, `facility_type` ASC)

这是推断的语法,未经测试,但假设 MySQL 中没有禁止复合外键的意外限制,它应该接近您的需要。

这个概念是您需要一个单一的外键引用,它指定 Facility 表中的两列引用被引用表中的匹配列。索引也需要在一对列上,而不是在单个列上。

关于mysql - 具有复合主键的外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17273644/

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