以下设置将:
products
这可能是因为条目是在products
之前categories_products
创建的。但在我知道产品ID之前,我无法在categories_products
中创建条目。
你会做什么?
ALTER TABLE products
ADD CONSTRAINT FK_products
FOREIGN KEY (id) REFERENCES categories_products(product_id)
ON UPDATE CASCADE
ON DELETE CASCADE;
表格
categories:
id, name
categories_products:
category_id, product_id
products:
id, name
每个条目的创建顺序
categories
和products
之间的关系答案 0 :(得分:0)
我认为你有你的约束。该外键应位于categories_products
表上并引用products
表,而不是相反:
ALTER TABLE categories_products
ADD CONSTRAINT FK_products
FOREIGN KEY (product_id) REFERENCES products(id)
ON DELETE CASCADE;
答案 1 :(得分:0)
您有多对多关系:
因此,您应该添加两个外键来支持这种类型的关系。必须将这些外来物添加到categories_products表中:
ALTER TABLE categories_products
ADD CONSTRAINT fk_products FOREIGN KEY (product_id)
REFERENCES products(id),
ADD CONSTRAINT fk_categories FOREIGN KEY (category_id)
REFERENCES categories(id);
然后,要删除类别和相关产品,请使用如下查询:
SET FOREIGN_KEY_CHECKS = 0;
DELETE c, cp, p
FROM category c
JOIN categories_products cp
ON cp.category_id = c.id
JOIN products p
ON p.id = cp.product_id
WHERE
c.id = 100;
SET FOREIGN_KEY_CHECKS = 1;
您还可以添加ON DELETE CASCADE子句,它将帮助您从父表中删除行并自动删除子表中的匹配行。例如,下一个查询将删除categories_products
表中的自动相关记录:
DELETE FROM category id = 100;