我是数据库算法的新手,不知道它是如何在内部工作的。
因此,我尝试编写以下两个查询来比较性能:
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
查询执行时间= 940ms。
我重写了如下查询:
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
查询执行时间为17321ms。
为什么时间差异如此之大?
答案 0 :(得分:2)
您有两个查询给出不同的结果,其中一个是外部联接查询,但另一个是内部联接查询。可能是你获得不同执行时间的原因。
对于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
当这些条件转移到ON
条款时,你会得到真实的OUTER JOIN
行为!