資料表關聯
最後更新
本頁說明 innerJoin()、leftJoin()、rightJoin() 的參數形式與產生的 SQL。
三種 JOIN
三個方法共用同一個內部實作 join()(src/MySQLPool.ts:151-174),只差在 JOIN 類型:
| 方法 | SQL |
|---|---|
innerJoin(table, first, operator, second?) |
INNER JOIN |
leftJoin(table, first, operator, second?) |
LEFT JOIN |
rightJoin(table, first, operator, second?) |
RIGHT JOIN |
參數形式
| 形式 | 範例 | 產生的 SQL |
|---|---|---|
| 三參數(等值) | innerJoin("users", "orders.user_id", "users.id") |
INNER JOIN `users` ON orders.user_id = users.id |
| 四參數(指定運算子) | leftJoin("p", "a", "!=", "b") |
LEFT JOIN `p` ON `a` != `b` |
三參數時,第三個參數被當成 second,運算子固定為 =。
const rows = await MySQLPool
.table("orders")
.select("orders.id", "users.name", "products.title")
.innerJoin("users", "orders.user_id", "users.id")
.leftJoin("order_items", "orders.id", "order_items.order_id")
.leftJoin("products", "order_items.product_id", "products.id")
.where("orders.status", "completed")
.get();
欄位與資料表名規則
| 對象 | 規則 |
|---|---|
| 被關聯的資料表 | 一律加反引號 |
first、second |
不含 . 時加反引號,含 . 時原樣輸出 |
多表查詢時欄位名容易重複,select() 與 where() 都使用 資料表.欄位 形式可避免欄位名稱不明確(ambiguous column)錯誤。