简体   繁体   English

使用主键索引在MySQL中删除行

[英]Delete rows in MySQL using primary key index

I am trying to delete many rows using primary key search. 我正在尝试使用主键搜索删除许多行。

eg 例如

DELETE FROM t1 WHERE t1.pid IN (SELECT pid FROM ...);

Here pid is primary key of table t1 but it is not using index in case of delete. pid是表t1主键,但是在删除的情况下不使用索引。
The inner query is returning too many rows so the whole query is taking too much time as outer one is not using index. 内部查询返回的行太多,因此整个查询要花费太多时间,因为外部查询没有使用索引。

How can I delete those rows faster? 如何更快地删除这些行?

You should avoid the subquery, but use JOIN instead: 您应该避免使用子查询,而应使用JOIN

DELETE t1
FROM t1 INNER JOIN t2 ON t1.pid = t2.pid
[WHERE .....]

Naturally t2 is the table you're getting pid from in your subquery; 自然地, t2是您从子查询中获取pid的表; consider you can also add the WHERE clause to limit selected (and so deleted) pids... 考虑到您还可以添加WHERE子句以限制所选(因此已删除)的pids ...
Also consider that pid column on t2 table should be indexed to speed up query... 还考虑到应该索引t2表上的pid列以加快查询速度...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM