在求和案例中使用 exists 子句 (oracle)

using exists clause in a sum case (oracle)

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

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)会节省一些时间,但不会太多。这不是完整的连接,但它仍然是部分连接;你无法避免。