使用其他表的列从表中删除
Posted
技术标签:
【中文标题】使用其他表的列从表中删除【英文标题】:Delete from table using column of other table 【发布时间】:2021-05-26 11:47:15 【问题描述】:我创建了一个过程,在该过程中我创建了一个临时表来存储列的值,然后我想使用这些列值来删除其他表中的数据。 如何在 while 循环中执行此操作,或者我可以使用 join 从 AppCoverLetter 中删除行,AppError 哪种方式更好?
CREATE DEFINER=`root`@`localhost` PROCEDURE `gdpr_delete`(_email_ varchar(128))
BEGIN
DECLARE NumberRecords int;
DECLARE RowCount int ;
-- Create a temporary table, note the IDENTITY
-- column that will be used to loop through
-- the rows of this table
CREATE TABLE GdprDeleteData (AppId INT NOT null);
-- Insert the resultset we want to loop through
-- into the temporary table
INSERT INTO GdprDeleteData (AppId) SELECT AppId FROM ApplyData.AppFormData where lower(Email) = lower(_email_);
-- Get the number of records in the temporary table
SET NumberRecords = ROW_COUNT();
SET RowCount = 1;
select NumberRecords, RowCount;
-- loop through all records in the temporary table
-- using the WHILE loop construct
start transaction;
DELETE AppCoverLetter FROM AppCoverLetter inner JOIN GdprDeleteData ON AppCoverLetter.AppID = GdprDeleteData.AppId;
DELETE AppError FROM AppError inner JOIN GdprDeleteData ON AppError.AppID = GdprDeleteData.AppId;
DELETE AppFormData FROM AppFormData inner JOIN GdprDeleteData ON AppFormData.AppID = GdprDeleteData.AppId;
DELETE AppJobData FROM AppJobData inner JOIN GdprDeleteData ON AppJobData.AppID = GdprDeleteData.AppId;
DELETE AppTrackingData FROM AppTrackingData inner JOIN GdprDeleteData ON AppTrackingData.AppID = GdprDeleteData.AppId;
DELETE FlowLog FROM FlowLog inner JOIN GdprDeleteData ON FlowLog.AppID = GdprDeleteData.AppId;
DELETE App FROM App inner JOIN GdprDeleteData ON App.AppID = GdprDeleteData.AppId;
DELETE AppCoverLetter FROM AppCoverLetter inner JOIN GdprDeleteData ON AppCoverLetter.AppID = GdprDeleteData.AppId;
DELETE AppResume FROM AppResume inner JOIN GdprDeleteData ON AppResume.AppID = GdprDeleteData.AppId;
commit;
-- drop the temporary table
drop table GdprDeleteData;
END
【问题讨论】:
你有什么问题? ..你有一个错误??显示错误消息..错误的结果更新您的问题添加正确的数据样本和预期的结果 我想知道当前使用连接删除哪种方式更好,或者我应该使用while循环进行操作 【参考方案1】:您可以避免临时表和循环 在 mysql 中,您可以在单个查询中从两个表中删除,并使用 sunquery 作为临时数据
DELETE t1, t2
FROM AppCoverLetter t1
INNER JOIN (
SELECT AppId
FROM ApplyData.AppFormData
where lower(Email) = lower(_email_)
) t3 ON t1.AppID = t3.AppId
INNER JOIN AppError t2 ON t2.AppID = t3.AppId;
或者如果你有更多的桌子
DELETE t1, t2, tx
FROM AppCoverLetter t1
INNER JOIN (
SELECT AppId
FROM ApplyData.AppFormData
where lower(Email) = lower(_email_)
) t3 ON t1.AppID = t3.AppId
INNER JOIN AppError t2 ON t2.AppID = t3.AppId
INNER JOIN table3 tx ON tx.AppID = t3.AppId;
【讨论】:
如果我有超过 2 张桌子怎么办,请检查有问题的编辑@scaisEdge 答案已更新..您只需要删除子句中的表引用和相关连接 它给出了不止一张表@scaisEdge的语法错误 删除了错误的;在第一个加入答案结束时更新.. 如果这3个表中有1个没有匹配条件/没有数据@scaisEdge,它不会删除数据以上是关于使用其他表的列从表中删除的主要内容,如果未能解决你的问题,请参考以下文章