在求和情况下使用 EXISTS 子句 (预言机)



我试图避免两个表之间非常昂贵的连接:我想知道使用 EXISTS 子句是否可以,因为我不需要显示第二个表中的任何字段。此时的代码是:

SELECT
t1.year, t1.month,
sum(case when (t1.flag1=0 and **t2.flag2=1**) then 1 else 0 end) as sum1
sum(case when (t1.flag1=1 and **t2.flag2=0**) then 1 else 0 end) as sum2
FROM
t1
**RIGHT JOIN t2 on (t1.uk1 = t2.uk2)**
GROUP BY
t1.year, t1.month

还没有找到任何可能的解决方案,我想知道是否有人知道如何去做。谢谢!

你是说uk2t2中的唯一键,所以你只需要找到是否存在一行t2.uk2 = t1.uk1t2.flag = 1然后连接可以停止 - 无需继续?

㞖:

SELECT
t1.year, t1.month,
sum(case when t1.flag1=0 and 
              t1.uk1 in (select t2.uk2 from t2 where t2.flag = 1)
              then 1 else 0 end)
FROM
t1
GROUP BY
t1.year, t1.month

请注意,半连接(使用 IN 或 EXISTS)将节省一些时间,但不会太多。它不是整个联接,但它仍然是部分联接;你无法避免这一点。

最新更新