我有很少的表,我想從PDF表中引用一列到多個其他表。 有可能引用一列作爲多個外鍵
例如,如果PDF表格select
輸出看起來是這樣的:
ITEM_TYPE ITEM_ID QUANTITY
1 23 3
2 12 1
它告訴我:
PDF有3個汽車輪產品,以及1汽車模板上面頭;
我寫的SQL代碼,但不能正常工作:
CREATE TABLE `pdf_created` (
`id` INT(10) UNSIGNED NOT NULL UNIQUE AUTO_INCREMENT,
`pdf_id` INT(10) NOT NULL,
`item_type` INT(3) UNSIGNED NOT NULL,
`item_id` INT(10) UNSIGNED NOT NULL,
`quantity` INT(3) NOT NULL,
PRIMARY KEY (`id`),
KEY `FK_pdf_id` (`pdf_id`),
CONSTRAINT `FK_pdf_id` FOREIGN KEY (`pdf_id`) REFERENCES `pdf` (`id`),
KEY `FK_item_type` (`item_type`),
CONSTRAINT `FK_item_type` FOREIGN KEY (`item_type`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
KEY `FK_item_id` (`item_id`),
CONSTRAINT `FK_item_id` FOREIGN KEY (`item_id`) REFERENCES `product` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `FK_item_id` FOREIGN KEY (`item_id`) REFERENCES `service` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `FK_item_id` FOREIGN KEY (`item_id`) REFERENCES `header` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `header` (
`id` INT(10) UNSIGNED NOT NULL UNIQUE AUTO_INCREMENT,
`title` VARCHAR(255),
`desc` VARCHAR(65535),
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `service` (
`id` INT(10) UNSIGNED NOT NULL UNIQUE AUTO_INCREMENT,
`desc` VARCHAR(65535) NOT NULL,
`price` DECIMAL(5,2) NOT NULL,
`active` INT(1) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `product` (
`id` INT(10) UNSIGNED NOT NULL UNIQUE AUTO_INCREMENT,
`category_id` INT(3) UNSIGNED NOT NULL,
`symbol` VARCHAR(255),
`desc` VARCHAR(65535),
`price` DECIMAL(5,2) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
有可能創造呢?
不,這是不可能的。您的外鍵必須指向一個表,它不能指向帶有外鍵的table1,table2或table3。 您可以在插入之前和更新觸發器之前檢查它是否存在於其中一個表 – 2013-03-21 12:20:29
Michael中,令人驚訝的是,某些DBMS可能在相同的字段上定義N> 1個外鍵並將它們指向不同的表。我剛剛在MySQL 5.5,Oracle 11g和MS SQL 2012中證實了這一點。我認爲使用該功能幾乎總是一個壞主意,但這不是不可能的(並且在多個表被引用爲父母都是同一個邏輯實體)。請參閱http://stackoverflow.com/questions/19057188/one-field-with-two-references-in-mysql/19057571#19057571 – 2013-09-30 12:47:02