首页 > 解决方案 > MySQL映射表插入约束不起作用

问题描述

我有一个客户和产品的映射表。以下是步骤

    create table `customer_products` (
       `customer_id` bigint not null,
        `product_id` bigint not null,
        primary key (`customer_id`, `product_id`)
    );

     alter table `customer_products` 
       add constraint `FK7urin54lem7yxy6umxf899t16` 
       foreign key (`customer_id`) 
       references `customer` (`customer_id`);

    alter table `customer_products` 
       add constraint `FKtfgjfwfykaef4wjk00ofyqq8y` 
       foreign key (`product_id`) 
       references `product` (`product_id`);

   insert into customer_products values(7,5); //should get a contraint error

当我插入此映射表时,虽然父表中没有相应的条目,但上述insert语句中没有错误。我需要一些额外的选项来设置这个约束吗?

标签: mysqlsql

解决方案


这种方法不好。但有一个解决方案。

You can write a trigger on customer_products and set 'before insert'

您需要编写更智能的查询来插入不存在记录的父表。


推荐阅读