嗨大家好我试图从三个表中删除多个记录。 但它没有按预期工作。
我的查询:
DELETE FROM offer, offer_products, offer_product_addons
USING offer, offer_products, offer_product_addons
WHERE offer.offer_number IS NULL
AND offer_products.offer_id = offer.id
AND offer_product_addons.offer_products_id = offer_products.id;
我的猜测是,当其他一个表中没有找到记录时,它不会删除记录。如何才能完成这项工作,我已尝试使用join,但只删除了主表中的内容。
答案 0 :(得分:1)
最好在多个操作上使用CASCADE
函数,即删除或更新。
CASCADE
- 如果ON UPDATE CASCADE
或ON UPDATE SET NULL
递归以更新它在级联期间之前更新的同一个表,则其行为类似于RESTRICT
。这意味着您不能使用自引用ON UPDATE CASCADE或ON UPDATE SET NULL
操作。这是为了防止级联更新导致的无限循环。另一方面,自我指涉ON DELETE SET NULL
是可能的,自我指称是ON DELETE CASCADE
。级联操作可能不会嵌套超过15级。
有时,从父表中删除数据时,了解哪个表受MySQL ON DELETE CASCADE
引用操作影响很有用。您可以从information_schema数据库中的referential_constraints查询此数据,如下所示:
<强>代码:强>
USE information_schema;
SELECT table_name
FROM referential_constraints
WHERE constraint_schema = 'database_name' AND
referenced_table_name = 'parent_table' AND
delete_rule = 'CASCADE'
示例:强>
例如,要使用 classicmodels 数据库中的CASCADE delete rule
查找与建筑物表关联的表格,请使用以下查询:
USE information_schema;
SELECT table_name
FROM referential_constraints
WHERE constraint_schema = 'classicmodels' AND
referenced_table_name = 'buildings' AND
delete_rule = 'CASCADE'
DELETE CASCADE
的另一个替代示例:
如果您的cascading deletes
核销产品,因为它是被杀的类别的成员,那么您就是不正确地设置了您的外键。根据您的示例表,您应该设置以下表格:
CREATE TABLE category (
id int unsigned not null primary key,
name VARCHAR(255) default null
)Engine=InnoDB;
CREATE TABLE product (
id int unsigned not null primary key,
name VARCHAR(255) default null
)Engine=InnoDB;
CREATE TABLE category_product (
category_id int unsigned not null,
product_id int unsigned not null,
PRIMARY KEY (category_id, product_id),
KEY pkey (product_id),
FOREIGN KEY (category_id) REFERENCES category (id)
ON DELETE CASCADE
ON UPDATE CASCADE,
FOREIGN KEY (product_id) REFERENCES product (id)
ON DELETE CASCADE
ON UPDATE CASCADE
)Engine=InnoDB;