2014-10-22 153 views
0

任何人都可以帮助我重写一个SQL查询,如下所示:有一个子查询需要重复。如何重写包含重复的子查询的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 
); 

谢谢!!

+0

设置一个变量子查询的值,然后重复引用您使用的是什么类型的SQL Server的子查询 – steoleary 2014-10-22 11:18:16

+1

的那个呢? sql-server,mysql ...? – ccheneson 2014-10-22 11:20:52

+0

是否需要在1个查询中? – ccheneson 2014-10-22 11:51:17

回答

2

这应该工作(假定MySQL的,也工作了甲骨文):

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; 
+0

@fancyPants ....我没有看到你的答案...好吧,我删除了我的答案。 – Karunakar 2014-10-22 12:15:50

+0

@fancyPants:我检查了你在Oracle上的查询,但是在“update policy p inner join”错误systax。谢谢 – latala 2014-10-23 04:35:33

+0

@latala错误消息说,实际的错误是在'update policy p ...'左边。你是否有任何机会在存储过程中运行它?提供完整的错误信息和代码,否则我们无法提供帮助。 – fancyPants 2014-10-23 07:08:14

2

我喜欢这一点,因为它很容易插入上述的一个选择,看看会有什么改变。

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] 
+0

谢谢,它在MySQL上工作,但在Oracle语法中更新是不同的:) – latala 2014-10-23 04:37:01