简体   繁体   English

使用WHERE EXISTS条件时的性能问题

[英]performance issue when using WHERE EXISTS condition

I have two tables that hold GBs of data. 我有两个表,用于保存GB的数据。

When I perform a query with "WHERE EXISTS ...", on either table, the whole MySQL goes down. 当我在任何一个表上使用“ WHERE EXISTS ...”执行查询时,整个MySQL都会崩溃。

Example of the query: 查询示例:

DELETE FROM `records`  
where exists (
    select * 
    from `measurements` 
    where `file_id` = 17
    and measurements.id = records.measurement_id
    ) 

I am not sure on where to start debugging or how this can be solved. 我不确定从哪里开始调试或如何解决。

Example of a query which works fine on the same server running on a different database, but takes forever on the main DB 一个查询示例,该查询在运行在不同数据库上的同一服务器上运行正常,但在主数据库上却永远存在

select * 
from `params` 
where exists (
    select * 
    from `records` 
    where `params`.`record_id` = `records`.`id` and exists (
        select * 
        from `measurements` 
        where `records`.`measurement_id` = `measurements`.`id`
            and `file_id` = 17"
    )
)

You simply perform DELETE on entire table if subquery returns any row: 如果子查询返回任何行,则只需对整个表执行DELETE

DELETE FROM `records`;

I believe you want correlated subquery: 我相信你想要相关的子查询:

DELETE FROM `records`  
where exists (
  select * 
  from `measurements` 
  where `file_id` = 17
   and `measurements`.col_name = `records`.col_name 
) ;

EDIT: 编辑:

You are correct about correlation part. 您对相关部分是正确的。 The query still taking DB down 查询仍然使数据库崩溃

You should check metrics (how many % of intital table you are removing). 您应该检查指标(要删除的初始表的百分比)。 If more than 20-30% I would simply use CTAs and recreate table. 如果超过20%到30%,我将简单地使用CTAs并重新创建表。

Second thing: you need to check FK ( ON DELETE CASCADE ) 第二件事:您需要检查FK( ON DELETE CASCADE

I had to rewrite query using LEFT JOINs to perform deletes. 我必须使用LEFT JOINs重写查询才能执行删除操作。 The reason why "exists" took too long is because "exists" has to check each record against the query. 之所以“存在”花费太长时间的原因是,“存在”必须对照查询检查每个记录。

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

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