我正在尝试使用例程(cID)通过CustomerID和phpMyAdmin从3个不同的表中删除客户及其订单。 我的表结构如下图所示: Tables structure 主键是CustomerID,OrderID,ProductID。
表:订单
表:客户
表:产品
表:已分配
以下查询:
BEGIN
INSERT INTO customersdeleted SELECT * FROM customers
WHERE CustomerID = cID; DELETE assigned
FROM assigned INNER JOIN orders
ON assigned.OrderID = orders.OrderID
WHERE orders.CustomerID = cID;
DELETE FROM customers WHERE customerID = cID;
SELECT * FROM orders;
SELECT * FROM customers; SELECT * FROM customersdeleted;
END
我多年来一直试图让这个查询工作,并通过CustomerID删除客户及其订单,并将它们(一旦删除)插入到我也创建的customersdeleted表中。 任何帮助将不胜感激!
答案 0 :(得分:0)
你在创建表时遇到一些问题; 我给你一个简单的代码解决方案:
create table order(
orderId varchar(10),
order_date date,
customerId char(7),
primary key(customerId)
);
create table customers(
customerId char(7),
customerName varchar(30),
primary key(customerId),
foreign key(customerId) references order(customerId),
on delete cascade
);
N:B:如果从订单表中删除客户ID,删除级联将删除所有表中的customerid。然后更改您的查询,以便您只需删除订单表的customerid,其他人将自动删除因为它们是外键。
答案 1 :(得分:0)
我能够使查询正常工作,并将删除的数据添加到特定的表中。在DELETE分配后,我才会失踪, 订单 。见下文。
BEGIN
INSERT INTO customersdeleted SELECT * FROM customers
WHERE CustomerID = cID;
DELETE assigned, orders
FROM assigned
INNER JOIN `orders` ON `assigned`.`OrderID` = `orders`.`OrderID`
WHERE `orders`.`CustomerID` = cID;
DELETE FROM `customers` WHERE `CustomerID` = cID;
SELECT * FROM orders;
SELECT * FROM customers;
SELECT * FROM assigned;
SELECT * FROM customersdeleted;
END