简体   繁体   English

为什么联接受限表比限制联接表快得多?

[英]Why is join the restricted tables much faster than restricting the joined tables?

I'm new in database algorithms and don't know how it works internally. 我是数据库算法的新手,不知道它在内部如何工作。

So, I tried to write the following two queries to compare the performance: 因此,我尝试编写以下两个查询来比较性能:

SELECT * 
FROM (
    SELECT *
    FROM account
    WHERE id < 20000
) as dpa_r
FULL OUTER JOIN (
    SELECT *
    FROM transactions
    WHERE id < 20000
) as pet_r
ON SOME_CONDITION
FULL OUTER JOIN (
    SELECT *
    FROM profit
    WHERE id < 20000
) as dp_r
ON SOME_CONDITION

OFFSET 200000 LIMIT 20

The query execution time = 940ms. 查询执行时间= 940ms。

I rewrote the query as follows: 我将查询重写如下:

SELECT * 
FROM (
    SELECT *
    FROM account
) as dpa_r
FULL OUTER JOIN (
    SELECT *
    FROM transactions
) as pet_r
ON SOME_CONDITION
FULL OUTER JOIN (
    SELECT *
    FROM profit
) as dp_r
ON SOME_CONDITION
WHERE dp_r.id < 20000 AND dpa_r.id < 20000 AND pet_r.id < 20000
OFFSET 200000 LIMIT 20

The query execution time is 17321ms. 查询执行时间为17321ms。

Why is there so difference in time? 为什么时间如此不同?

You're two queries give different results, one of them is an outer join query, but the other one is an inner join query. 您有两个查询给出不同的结果,其中一个是外部联接查询,但是另一个是内部联接查询。 Probably the reason why you get different execution times. 可能是您获得不同执行时间的原因。

With column conditions in the WHERE clause, your outer joins perform as regular inner joins: 使用WHERE子句中的列条件,您的外部联接将像常规内部联接一样执行:

SQL>create table t1 (c1 int, c2 char(10));
SQL>create table t2 (c1 int, c2 char(10));
SQL>insert into t1 values (1,'One');
SQL>insert into t1 values (2,'Two');
SQL>insert into t2 values (1,'One');
SQL>insert into t2 values (5,'Five');
SQL>select * from t1 left join t2 on t1.c1 = t2.c1
SQL&where t1.c1 < 10 and t2.c1 < 10;
         c1 c2                  c1 c2
=========== ========== =========== ==========
          1 One                  1 One

                  1 row found

SQL>select * from t1 left join t2 on t1.c1 = t2.c1 
SQL&  and t1.c1 < 10 and t2.c1 < 10;
         c1 c2                  c1 c2
=========== ========== =========== ==========
          1 One                  1 One
          2 Two                  - -

                  2 rows found

When those conditions were moved to the ON clause, you get true OUTER JOIN behavoir! 当这些条件移到ON子句时,您将获得真正的OUTER JOIN行为!

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

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