如何重写包含重复SubQuery的SQL查询?

时间:2014-10-22 11:13:35

标签: sql oracle

有没有人可以帮我改写SQL查询,如下所示?有一个子查询要重复。

update policy 
set totalvehicles = (
  select count(*) from riskunit 
  where riskunit.policyId = policy.id
  and riskunit.subtype = 7) 
where policy.verified = '1' 
and policy.Totalvehicles <(
  select count(*) 
  from riskunit 
  where riskunit.policyId = policy.id 
  and riskunit.subtype = 7
); 

谢谢!

2 个答案:

答案 0 :(得分:2)

这应该有效(假设MySQL,也适用于Oracle):

update policy p
inner join (
  select policyId, count(*) as n from riskunit 
  where riskunit.subtype = 7
  group by policyId
) ru on ru.policyId = p.id
set p.totalvehicles = ru.n
where p.verified = '1' 
and p.Totalvehicles < ru.n;

答案 1 :(得分:2)

我更喜欢这个,因为很容易在from上面插入一个select,看看会有什么变化。

UPDATE p 
SET totalvehicles = cnt.[Count]
FROM policy p
INNER JOIN (
    SELECT
        policyId,COUNT(*) [Count]
    FROM riskunit
    WHERE ru.subtype = 7
    GROUP BY policyId
) cnt on cnt.policyId=p.policyId
WHERE p.verified = '1'
AND p.Totalvehicles < cnt.[Count]