删除 Access 中不匹配的记录
我在 Access 数据库中有一个表,其中的记录可以从其他两个表中的任何一个引用。如果其他任何一个表都没有引用它们,我需要从该表中删除记录。 到目前为止,我最好的解决方案是创建一个子查询来返回引用记录的 id 并从删除查询中引用子查询。 (子查询必须是单独的,因为 Access 不允许在嵌套子查询中使用 UNION。)
所以 ...
SelectQuery:
SELECT TableB.id FROM TableB INNER JOIN TableA ON TableB.id = TableA.id
UNION
SELECT TableC.id FROM TableC INNER JOIN TableA ON TableC.id = TableA.id
DeleteQuery:
DELETE * FROM TableA WHERE id NOT IN (SELECT * FROM SelectQuery)
这太慢了......一定有更好的方法吗?
我试图避免向 TableA 添加布尔“Used
”字段...
I have a table in an Access database where records may be referenced from either of two other tables. I need to delete records from that table if they are not referenced by either of the others.
My best solution so far has been to create a subquery to return the id's of the referenced records and to refer to the subquery from a delete query. (The subquery has to be separate because Access does not allow UNION in nested subqueries.)
So ...
SelectQuery:
SELECT TableB.id FROM TableB INNER JOIN TableA ON TableB.id = TableA.id
UNION
SELECT TableC.id FROM TableC INNER JOIN TableA ON TableC.id = TableA.id
DeleteQuery:
DELETE * FROM TableA WHERE id NOT IN (SELECT * FROM SelectQuery)
This is excruciatingly slow ... there must be a better way?
I was trying to avoid having to add a boolean 'Used
' field to TableA ...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
@Matthew PK 建议使用两个 NOT IN 子查询,这在理论上是一个好主意,但正如我在评论中观察到的那样,NOT IN 和 NOT EXISTS 被 Jet/ACE 优化得很差,并且通常不会使用比较两侧的索引。我想知道子查询是否有必要:
这肯定会使用您的索引。如果需要子查询,可以将TableB和TableC替换为相关的子查询。
@Matthew PK suggests using two NOT IN subqueries, which is theoretically a good idea, but as I observed in a comment, NOT IN and NOT EXISTS are poorly optimized by Jet/ACE and will often not use the indexes on both sides of the comparison. I'm wondering whether or not subqueries are necessary or not:
This would definitely use your indexes. If a subquery is necessary, you could replace TableB and TableC with the relevant subqueries.
为什么不是这样的:
?
Why not something like this:
?
是否可以根据您的 SelectQuery 创建一个新表,删除原始表,然后将新表重命名为原始名称?
Is it acceptable to create a new table based on your SelectQuery, delete the original table, and rename the new one to the original name?