Principle:APIJSON APIJSON Multi Table Join
| Knowledge Sources | |
|---|---|
| Domains | ORM, SQL_Join, Multi_Table_Query |
| Last Updated | 2026-10-11 00:00 GMT |
Overview
A query composition pattern that combines data from multiple database tables in a single request, using either SQL JOIN clauses for database-level joins or application-level batch queries for performance-sensitive scenarios.
Description
Multi-Table Join is the ability to fetch related data from multiple tables in a single API request. APIJSON supports two distinct join strategies:
SQL JOINs: Traditional SQL JOIN clauses (LEFT, RIGHT, INNER, CROSS, FULL, OUTER) are generated in the SQL string and executed by the database. This is efficient for one-to-one and many-to-one relationships but can produce large result sets for one-to-many joins.
APP JOINs: Application-level joins that execute separate queries for each table and merge results in code. The main table is queried first, then the joined table is queried with WHERE id IN (collected_ids). This is more efficient for one-to-many relationships because it avoids row multiplication.
The choice between SQL JOIN and APP JOIN is made by the client via the join type character in the @join directive:
- "<", ">", "&" etc. → SQL JOIN (generated in SQL)
- "@ → APP JOIN (application-level batch query)
The problem solved is the N+1 query problem: fetching a list of records and their related records without requiring N+1 API calls. With multi-table join, a single request fetches all related data.
Usage
Use this principle when:
- An API response needs data from multiple related tables
- Different join strategies are needed for different relationships
- Performance optimization requires choosing between SQL and application-level joins
Theoretical Basis
# Abstract algorithm (NOT real implementation):
def execute_multi_table_join(main_query, join_list):
sql_joins = [j for j in join_list if j.type != "@"]
app_joins = [j for j in join_list if j.type == "@"]
# Phase 1: Execute main query with SQL JOINs
if sql_joins:
sql = generate_select_with_joins(main_query, sql_joins)
results = execute_sql(sql)
else:
results = execute_sql(main_query.to_sql())
# Phase 2: Execute APP JOINs (application-level batch)
for join in app_joins:
# Collect foreign key values from main results
fk_values = [r[join.on.target_key] for r in results]
# Batch query joined table
child_sql = f"SELECT * FROM {join.table} WHERE {join.on.key} IN ({fk_values})"
child_results = execute_sql(child_sql)
# Merge child results into main results
for r in results:
r[join.table] = find_children(child_results, join.on, r)
return results