2013-06-24 233 views
1

表中有一列引用另一個表列,該列是複合主鍵。 如何爲此編寫查詢? 它顯示此錯誤。我該如何解決它。帶複合主鍵的外鍵

錯誤1050:無法創建表(錯誤:150) 'recdesk#SQL-5e8_33。'

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 
+3

如果引用的主鍵是合成的,則引用鍵也應該是合成的 –

回答

0

的錯誤是

ERROR 1050: Table 'facility' already exists

您需要在執行創建腳本之前刪除表。

3

如果表Facility一對列(Organization_ID, Facility_ID)的是一對錶中的Facility_Type(Organization_ID, Facility_ID)的外鍵引用,這是在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表中引用引用表中的匹配列的兩列。索引還需要在一對列上,而不是在一列上。