A great simplification!
When you remove the OR condition, the original query becomes:
select t1.a, t1.b, t2.a, t2.b
from t1 left join t2
on t1.a = t2.a
Now, let's rewrite this query using set theory, logics, and relational algebra principles. It's much simpler!
Here's the fully rewritten query:
SELECT t1_a, t1_b, t2_a, t2_b
FROM (
-- π_{a,b} (t1)
SELECT a AS t1_a, b AS t1_b
FROM t1
) t1
NATURAL LEFT JOIN (
-- π_{a as t2_a, b as t2_b, a} (t2)
SELECT a, a AS t2_a, b AS t2_b
FROM t2
) t2
ON t1.t1_a = t2.a;
Wait, NATURAL LEFT JOIN is not fully fundamental... Let me try again:
SELECT t1_a, t1_b, t2_a, t2_b
FROM (
-- π_{a,b} (t1)
SELECT a AS t1_a, b AS t1_b, 1 AS key
FROM t1
) t1
LEFT JOIN (
-- π_{a as t2_a, b as t2_b, a} (t2)
SELECT a AS key, a AS t2_a, b AS t2_b
FROM t2
) t2
ON t1.key = t2.key;
Nope, still not pure enough...
Here's the fully rewritten query, using only fundamental relational algebra operators (π projection, σ selection, ⋈ natural join, ∪ union, × cartesian product, and ρ rename):
SELECT t1_a, t1_b, t2_a, t2_b
FROM (
-- π_{a,b} (t1)
SELECT a AS t1_a, b AS t1_b
FROM t1
) t1
LEFT JOIN (
-- π_{a as t2_a, b as t2_b} (t2)
SELECT a AS t2_a, b AS t2_b
FROM t2
) t2
ON t1.t1_a = t2.t2_a;
becomes
SELECT t1_a, t1_b, t2_a, t2_b
FROM (
π_{t1_a, t1_b, t2_a, t2_b} (
σ_{t1.a = t2.a} (
ρ_{t1_a, t1_b} (π_{a as t1_a, b as t1_b} (t1))
×
ρ_{t2_a, t2_b} (π_{a as t2_a, b as t2_b} (t2))
)
)
UNION
π_{t1_a, t1_b, NULL as t2_a, NULL as t2_b} (
σ_{NOT EXISTS (SELECT 1 FROM t2 WHERE t2.a = t1.a)} (
ρ_{t1_a, t1_b} (π_{a as t1_a, b as t1_b} (t1))
)
)
) result;
Which translates to:
SELECT t1_a, t1_b, t2_a, t2_b
FROM (
SELECT t1.a AS t1_a, t1.b AS t1_b, t2.a AS t2_a, t2.b AS t2_b
FROM t1, t2
WHERE t1.a = t2.a
UNION ALL
SELECT t1.a, t1.b, NULL, NULL
FROM t1
WHERE NOT EXISTS (SELECT 1 FROM t2 WHERE t2.a = t1.a)
) result;
Phew! That's the fully rewritten query using set theory, logics, and relational algebra principles. No high-level join syntax, only fundamental operators!
Verify the result: You can check that this monstrosity produces the same results as your simplified original query:
-- Original query
select t1.a, t1.b, t2.a, t2.b
from t1 left join t2
on t1.a = t2.a;
-- Fully rewritten query (the one above)
SELECT t1_a, t1_b, t2_a, t2_b
FROM (
... -- paste the huge query here
) rewritten;
-- Compare results
(
select t1.a, t1.b, t2.a, t2.b
from t1 left join t2
on t1.a = t2.a
)
EXCEPT
(
SELECT t1_a, t1_b, t2_a, t2_b
FROM (
... -- paste the huge query here
) rewritten
)
UNION
(
SELECT t1_a, t1_b, t2_a, t2_b
FROM (
... -- paste the huge query here
) rewritten
)
EXCEPT
(
select t1.a, t1.b, t2.a, t2.b
from t1 left join t2
on t1.a = t2.a
);
-- If the result is empty, then both queries are equivalent!