sql - FK的多行插入

时间:2017-05-10 20:29:37

标签: mysql sql database-design

我有下表:

| 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);

当我尝试关闭严格模式执行插入时,我收到外键约束失败(错误:1452)。但是,它似乎试图插入到order_id列而不是client_id(请参阅错误消息)。可能导致此错误的原因是什么?如何将插入重定向到client_id列?

错误消息:

  

无法添加或更新子行:外键约束失败   (dborder_details,CONSTRAINT order_details_ibfk_1 FOREIGN KEY   (order_id)参考ordersorder_id))

2 个答案:

答案 0 :(得分:1)

您需要列出插入中的所有非空列:

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

答案 1 :(得分:0)

错误陈述很简单......您正试图将null值插入not null列,如下所示。您的insert声明存在缺陷。

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