|
| 1 | +# Joining Tables |
| 2 | + |
| 3 | +`perspective.join()` creates a read-only `Table` by joining two source tables on |
| 4 | +a shared key column. The result is reactive — it updates automatically when |
| 5 | +either source table changes. See [`Join`](../../explanation/join.md) for |
| 6 | +conceptual details. |
| 7 | + |
| 8 | +## Basic Inner Join |
| 9 | + |
| 10 | +```javascript |
| 11 | +const orders = await perspective.table([ |
| 12 | + { id: 1, product_id: 101, qty: 5 }, |
| 13 | + { id: 2, product_id: 102, qty: 3 }, |
| 14 | + { id: 3, product_id: 101, qty: 7 }, |
| 15 | +]); |
| 16 | + |
| 17 | +const products = await perspective.table([ |
| 18 | + { product_id: 101, name: "Widget" }, |
| 19 | + { product_id: 102, name: "Gadget" }, |
| 20 | +]); |
| 21 | + |
| 22 | +const joined = await perspective.join(orders, products, "product_id"); |
| 23 | +const view = await joined.view(); |
| 24 | +const json = await view.to_json(); |
| 25 | +// [ |
| 26 | +// { product_id: 101, id: 1, qty: 5, name: "Widget" }, |
| 27 | +// { product_id: 101, id: 3, qty: 7, name: "Widget" }, |
| 28 | +// { product_id: 102, id: 2, qty: 3, name: "Gadget" }, |
| 29 | +// ] |
| 30 | +``` |
| 31 | + |
| 32 | +## Join Types |
| 33 | + |
| 34 | +Pass `join_type` in the options to select inner, left, or outer join behavior: |
| 35 | + |
| 36 | +```javascript |
| 37 | +// Left join: all left rows, nulls for unmatched right columns |
| 38 | +const left_joined = await perspective.join(left, right, "id", { |
| 39 | + join_type: "left", |
| 40 | +}); |
| 41 | + |
| 42 | +// Outer join: all rows from both tables |
| 43 | +const outer_joined = await perspective.join(left, right, "id", { |
| 44 | + join_type: "outer", |
| 45 | +}); |
| 46 | +``` |
| 47 | + |
| 48 | +## Reactive Updates |
| 49 | + |
| 50 | +The joined table recomputes automatically when either source table is updated: |
| 51 | + |
| 52 | +```javascript |
| 53 | +const left = await perspective.table([{ id: 1, x: 10 }]); |
| 54 | +const right = await perspective.table([{ id: 2, y: "b" }]); |
| 55 | + |
| 56 | +const joined = await perspective.join(left, right, "id"); |
| 57 | +const view = await joined.view(); |
| 58 | + |
| 59 | +let json = await view.to_json(); |
| 60 | +// [] — no matching keys yet |
| 61 | + |
| 62 | +await right.update([{ id: 1, y: "a" }]); |
| 63 | +json = await view.to_json(); |
| 64 | +// [{ id: 1, x: 10, y: "a" }] — new match detected |
| 65 | +``` |
0 commit comments