mysql - 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
语句中没有错误。我需要一些额外的选项来设置这个约束吗?
解决方案
这种方法不好。但有一个解决方案。
You can write a trigger on customer_products and set 'before insert'
您需要编写更智能的查询来插入不存在记录的父表。
推荐阅读
- c++ - 给定一组带有线段的点,找到等距的点
- javascript - 在javascript中格式化数据
- javascript - 函数参数的可能值列表
- php - 从数据库中获取值;但是,未提交所选值
- linux - 在 Linux 上运行 .net Core Web Api
- python - 为我的 Django 项目创建主题标签系统后,保险箱无法正常工作
- django - 我可以在已经创建的带有用户数据的 mysql 数据库中使用 django 身份验证吗?
- firefox - Firefox 在预加载字体上显示警告,尽管它们在第一秒内使用
- c - GDB点运算符引用指针?
- python-3.x - Scrapy xpath 没有解析它应该解析的内容