2017-05-10 93 views
0

我有如下表:SQL - 多行插入的FK

| order_details | CREATE TABLE `order_details` (
    `order_id` int(11) NOT NULL, 
    `client_id` int(11) NOT NULL, 
    `product_id` varchar(10) NOT NULL, 
    `serial` int(11) NOT NULL, 
    `detail_id` int(11) NOT NULL AUTO_INCREMENT, 
    PRIMARY KEY (`detail_id`), 
    KEY `order_id` (`order_id`), 
    KEY `client_id` (`client_id`), 
    CONSTRAINT `order_details_ibfk_1` FOREIGN KEY (`order_id`) REFERENCES `orders` (`order_id`), 
    CONSTRAINT `order_details_ibfk_2` FOREIGN KEY (`client_id`) REFERENCES `clients` (`client_id`) 
) ENGINE=InnoDB AUTO_INCREMENT=57 DEFAULT CHARSET=utf8 | 

我試圖插入在CLIENT_ID列值下降多行:

insert into order_details 
    (`client_id`) 
    values 
    (1), 
    (1), 
    (1), 
    (1), 
    (2), 
    (3), 
    (14), 
    (4), 
    (5), 
    (5), 
    (5), 
    (5), 
    (7), 
    ... 
    (12), 
    (13); 

當我嘗試執行插入嚴格模式關閉,我收到一個外鍵約束失敗(Err:1452)。但是,它似乎試圖插入到order_id列而不是client_id(請參閱err msg)。什麼可能導致這個錯誤,以及如何將插入重定向到client_id列?

錯誤消息:

不能添加或更新子行,外鍵約束失敗 (dborder_details,約束order_details_ibfk_1 FOREIGN KEY (order_id)參考文獻ordersorder_id)。)

回答

1

你需要列出在插入所有非空列:

insert into order_details 
    (`client_id`, [other columns here]) 
values 
(1, [other values here]), 
+0

完美,謝謝。如果我已經有這些字段的值,並且不想覆蓋它們,我應該只傳遞null? –

+0

@RayFoo你如何在這些領域有價值?這些是您創建的新行。 – Barmar

+0

另一種選擇是在CREATE TABLE語句中聲明一個DEFAULT值。 – Barmar

0

錯誤說明非常簡單...您正試圖將null的值插入not null列下面的。您的insert聲明有缺陷。

order_id int(11) NOT NULL 
    `product_id` varchar(10) NOT NULL, 
    `serial` int(11) NOT NULL,