2015-03-31 62 views
0

您好我有3個屬性作爲主鍵 產品的表: PRIMARY KEY(product_namecategoryproduct_type)。MySQL的複合外鍵引用超過2個屬性

現在我在另一個表引用此複合主鍵

ORDER_DETAILS: 外鍵(PRODUCT_NAME,產品類型,類別)引用的產品(PRODUCT_NAME,產品類型,類別)

但是我得到一個錯誤在控制檯說遺漏括號,我無法添加外鍵。但是,如果我只在參考中添加2個列名(例如:「外鍵(product_name,product_type,category)引用產品(product_name,product_type) 」),則查詢不會發生錯誤。

請幫我解決這個問題。請在下面找到

 
CREATE TABLE `products` (
    `product_name` varchar(45) NOT NULL, 
    `product_type` varchar(45) NOT NULL, 
    `category` varchar(45) NOT NULL, 
    `product_desc` varchar(150) DEFAULT NULL, 
    `unit_price` int(11) NOT NULL, 
    `supplier_id` int(11) NOT NULL, 
    `units_in_stock` int(11) NOT NULL, 
    PRIMARY KEY (`product_name`,`category`,`product_type`), 
    INDEX (product_name,category,product_type), 
    CONSTRAINT `supplier_prod_table_fkey` FOREIGN KEY (`supplier_id`) REFERENCES 
    `supplier` (`supplier_id`) ON DELETE NO ACTION ON UPDATE NO ACTION 
) ENGINE=INNODB; 

CREATE TABLE `order_details` (
    `order_id` int(11) NOT NULL AUTO_INCREMENT, 
    `product_name` varchar(45) NOT NULL, 
    `product_type` varchar(45) NOT NULL, 
    `category` varchar(45) NOT NULL, 
    `quantity` int(11) DEFAULT NULL, 
    CONSTRAINT `orderid_fkey` FOREIGN KEY (`order_id`) REFERENCES `orders` 
    (`order_id`) ON DELETE NO ACTION ON UPDATE NO ACTION, 
    PRIMARY KEY (`order_id`,`product_name`,`product_type`,`category`), 
    INDEX (product_name,product_type,category), 
    foreign key(product_name,product_type,category) references products(product_name,product_type,category) 

); 

回答

0

場我的代碼在REFERENCES和記者指數必須以相同的順序去兩個表中,即(product_name, category, product_type)

CREATE TABLE `order_details` (
    `order_id` int(11) NOT NULL AUTO_INCREMENT, 
    `product_name` varchar(45) NOT NULL, 
    `product_type` varchar(45) NOT NULL, 
    `category` varchar(45) NOT NULL, 
    `quantity` int(11) DEFAULT NULL, 
    CONSTRAINT `orderid_fkey` FOREIGN KEY (`order_id`) REFERENCES `orders` 
    (`order_id`) ON DELETE NO ACTION ON UPDATE NO ACTION, 
    PRIMARY KEY (`order_id`,`product_name`,`product_type`,`category`), 
    INDEX (product_name,category,product_type), 
    FOREIGN KEY(product_name,category,product_type) REFERENCES products(product_name,category,product_type) 

); 
+0

我試過了。但仍然無法正常工作:( – user2552729 2015-04-04 07:11:07

+0

@ user2552729仔細檢查,確實有效,這是[小提琴](http://sqlfiddle.com/#!9/2ea3c)。 – saaj 2015-04-06 09:38:32