gpt4 book ai didi

mysql - 删除另一个表中未使用的记录

转载 作者:行者123 更新时间:2023-11-29 23:16:49 25 4
gpt4 key购买 nike

我必须从 mysql 的一个表中删除许多记录。但某些记录与其他记录具有外键关系。因此,当我触发删除命令时,它会显示有关外键的错误,并回滚整个删除事务(这是自然的)。在这种情况下,我必须过滤其他表中使用(引用)的记录​​,然后删除。为什么不做过滤就删除记录?意味着如果我触发删除命令,删除那些未使用(引用)的记录​​,并跳过另一个表中使用的记录,而不显示错误或回滚。

最佳答案

使用左连接检查关系并删除所有没有关系的记录

delete t1
from tableToDeleteFrom t1
left join referenceTable t2 on t1.foreignKeyColumn = t2.keyColumn
where t2.keyColumn is null
and <your delete conditions>

如果您想要一个快速而肮脏的解决方案,您可以使用ignore关键字来忽略执行期间的错误:

The IGNORE keyword causes MySQL to ignore errors during the process of deleting rows. (Errors encountered during the parsing stage are processed in the usual manner.) Errors that are ignored due to the use of IGNORE are returned as warnings.

delete ignore from tableToDeleteFrom
where <your delete conditions>

关于mysql - 删除另一个表中未使用的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27717143/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com