❖ RA Operations to Combine Relations |
Relational algebra has several ways to combine info from relations
Frequently, primary-key joined with foreign-key
❖ Product |
Product (Cartesian product) combines information from two relations pairwise on tuples.
Each tuple in the result contains all attributes from r and s, possibly with some fields renamed to avoid ambiguity.
If t1 = (A1...An) and t2 = (B1...Bn) then (t1:t2) = (A1...An,B1...Bn)
Result size is large: |r × s| = |r|.|s| Schema: R∪S
Algorithmic view:
result = {} for each tuple t1 in relation r for each tuple t2 in relation s result = result ∪ {(t1:t2)} }
❖ Natural Join |
Natural join is a specialised product:
The natural join of relations r(R) and s(S) is defined as:
where match = t1[K] = t2[K] ∧ t1[L] = t2[L] ∧ t1[M] = t2[M]
Algorithmic view:
result = {} for each tuple t1 in relation r for each tuple t2 in relation s if (matches(t1,t2)) result = result ∪ {combine(t1,t2)}
❖ Theta Join |
The theta join is a specialised product containing only pairs that match on a supplied condition C.
Examples: (r1 Join[B>E] r2) ... (r1 Join[E<D∧C=G] r2)
All attribute names are required to be distinct (cf natural join)
Can be defined in terms of other RA operations:
Note that r ⨝true s = r × s.
❖ Theta Join (cont) |
Example theta join:
(Theta join is the most frequently-used join in SQL queries)
❖ Theta Join (cont) |
Querying with relational algebra (join) ...
NewtownBars(nbar) = Sel[addr=Newtown](Bars) Tmp = Frequents Join[bar=nbar] NewtownBars Result(drinker) = Proj[drinker](Tmp)
CarltonBeers = Sel[manf=Carlton](Beers) Tmp = Likes Join[beer=name] CarltonBeers Result(drinker) = Proj[drinker)Tmp
Reminder: projection removes duplicates
❖ Outer Join |
R ⨝C S does not include in its result
Variants are right outer join and full outer join
❖ Division |
Consider two relation schemas R and S where S ⊂ R.
The division operation is defined on instances r(R), s(S) as:
where satisfy = ∀ ts ∈ S ( ∃ tr ∈ R ( tr[S] = ts ∧ tr[R-S] = t ) )
Operationally:
❖ Division (cont) |
Querying with relational algebra (division) ...
Division handles queries that include the notion "for all".
E.g. Which beers are sold in all bars?
We can answer this as follows:
Produced: 11 Nov 2020