MySql删除客户&来自多个表的订单

时间:2017-04-11 15:06:55

标签: mysql phpmyadmin

我正在尝试使用例程(cID)通过CustomerID和phpMyAdmin从3个不同的表中删除客户及其订单。 我的表结构如下图所示: Tables structure 主键是CustomerID,OrderID,ProductID。

表:订单

  • OrderID
  • OrderDate
  • 客户id

表:客户

  • 客户id
  • 客户名称
  • 客户地址

表:产品

  • 的ProductID
  • ProductDesc
  • ProductPrice

表:已分配

  • ProductID(外键)
  • OrderID(外键)
  • 数量

以下查询:

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表中。 任何帮助将不胜感激!

2 个答案:

答案 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