我需要删除DB中某些表的子数据(映射的外键约束)。所以,实际上,我想将返回的SELECT查询的值传递给DELETE语句。
以下是我创建的存储过程,请帮助我了解这一点,并举例说明从表中删除子行。
delimiter //
create procedure deleteCustomerDeps(in emailAddr varchar(50))
begin
select customer_id into custId
from customer
where customer_id=emailAddr;
set @custoId=custId;
delete from customer where customer_id='@custoId';
prepare stmt from @custoId;
execute stmt;
deallocate prepare stmt;
end //
delimiter ;
... TIA
答案 0 :(得分:1)
假设您有以下架构
CREATE TABLE customers
(
customer_id INT,
customer_email VARCHAR(17),
PRIMARY KEY (customer_id)
);
CREATE TABLE child_table
(
child_id INT,
customer_id INT,
value INT,
PRIMARY KEY (child_id),
FOREIGN KEY (customer_id) REFERENCES customers (customer_id)
);
现在要删除所有知道客户电子邮件的子记录,您可以使用多表删除语法
CREATE PROCEDURE deleteCustomerData(IN emailAddr VARCHAR(50))
DELETE t
FROM child_table t JOIN customers c
ON t.customer_id = c.customer_id
WHERE c.customer_email = emailAddr;
这是 SQLFiddle 演示
...但是如果我想将SELECT stmt的返回值传递给DELETE ...
这正是你在上面提到的例子中所做的。但你总是可以这样重写它
DELETE t
FROM child_table t JOIN
(
SELECT customer_id
FROM customers JOIN ...
WHERE customer_email = emailAddr
AND ...
) c
ON t.customer_id = c.customer_id
或
DELETE
FROM child_table
WHERE customer_id IN
(
SELECT customer_id
FROM customers JOIN ...
WHERE customer_email = emailAddr
AND ...
)