简体   繁体   English

避免完全扫描子查询

[英]Avoid full scan for subquery

I have a query which was working before I added the exist condition. 在添加存在条件之前,我有一个正在运行的查询。 After adding the exist condition , its going into loop forever and not getting back any results. 添加存在条件后,它会永远进入循环并且不会返回任何结果。 I think the main reason for that is the full scan for every row level record. 我认为主要原因是对每个行级别的记录进行全面扫描。 Can anyone please tell how to avoid that. 谁能告诉我如何避免这种情况。 The query below is an example of what I am trying to achieve. 下面的查询是我要实现的示例。

Basically the condition is that a car can have many parts and if any one of the parts updated on changes for that car, we want to pick up all the parts. 基本上,条件是一辆汽车可以有很多零件,并且如果其中任何一个零件因该车的更改而更新,我们希望拿走所有零件。 The part has detail table and I want to look at updates to the detail table. 该零件具有明细表,我想查看对明细表的更新。

select c.id, p.id
from car c join part p on p.car_id=c.id
where exists ( 
    select 1 
    from part p join pdetl pd on p.id=pd.part_id 
    where p.car_id=c.id and pd.updated_on > ?
)

EDITED: Modified the query to get all the parts associated to the car that had part(s) updated. 编辑:修改查询以获取与汽车相关的所有具有更新零件的零件。

The inner query gets the parts that were updated. 内部查询获取已更新的部分。 The outer query then pulls all the parts that are associated to the car: 然后,外部查询将提取与汽车关联的所有零件:

select c.id, p.id
from car c join part p on p.car_id=c.id
where c.id in
(
  select c.id
  from car c join part p on p.car_id=c.id
  where exists ( 
                 select 1 
                 from pdetl pd 
                 where p.id=pd.part_id 
                   and pd.updated_on > ?
                )
)

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

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