Join
Join
A SQL operation that combines two or more tables on a specific condition to query data, with various types such as INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL OUTER JOIN.
Join
A SQL operation that combines two or more tables on a specific condition to query data, with various types such as INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL OUTER JOIN.
Join is a core operation in relational databases that combines data from multiple normalized tables. Based on the relationships between tables (mainly foreign keys), it builds related data into a single result set, making it possible to efficiently query complex information without data duplication.
The most commonly used INNER JOIN returns only the rows that satisfy the join condition in both tables. LEFT JOIN (LEFT OUTER JOIN) returns all rows from the left table along with the matching rows from the right table, and fills in NULL where there is no match. RIGHT JOIN is the opposite, and FULL OUTER JOIN returns all rows from both tables.
Join performance optimization is at the core of database tuning. Performance improves when you create indexes on join columns, SELECT only the necessary columns, and filter data first with a WHERE clause. By analyzing the query execution plan (EXPLAIN), you can check which algorithm among Nested Loop, Hash Join, and Merge Join is being used and optimize accordingly.
In modern ORMs (Object-Relational Mapping), joins are provided in an abstracted form. Examples include SQLAlchemy's join(), Django ORM's select_related(), and JPA's @JoinColumn. However, to avoid the N+1 problem and write efficient queries, it is important to understand the SQL that is actually generated.
-- ์์ ํ
์ด๋ธ ๊ตฌ์กฐ
-- users: id, name, email
-- orders: id, user_id, product_name, amount, created_at
-- ============================================
-- INNER JOIN: ๋ ํ
์ด๋ธ์ ๋ชจ๋ ์๋ ๋ฐ์ดํฐ๋ง
-- ============================================
SELECT
u.name,
u.email,
o.product_name,
o.amount
FROM users u
INNER JOIN orders o ON u.id = o.user_id
WHERE o.created_at >= '2024-01-01';
-- ๊ฒฐ๊ณผ: ์ฃผ๋ฌธ์ด ์๋ ์ฌ์ฉ์๋ง ์กฐํ๋จ
-- ============================================
-- LEFT JOIN: ์ผ์ชฝ ํ
์ด๋ธ(users)์ ๋ชจ๋ ํ ํฌํจ
-- ============================================
SELECT
u.name,
u.email,
COALESCE(o.product_name, '์ฃผ๋ฌธ ์์') AS product,
COALESCE(o.amount, 0) AS amount
FROM users u
LEFT JOIN orders o ON u.id = o.user_id;
-- ๊ฒฐ๊ณผ: ์ฃผ๋ฌธ์ด ์๋ ์ฌ์ฉ์๋ NULL ๊ฐ๊ณผ ํจ๊ป ์กฐํ๋จ
-- ============================================
-- ๋ค์ค ํ
์ด๋ธ JOIN
-- ============================================
-- products: id, name, category_id, price
-- categories: id, name
SELECT
u.name AS customer_name,
o.created_at AS order_date,
p.name AS product_name,
c.name AS category_name,
o.amount
FROM users u
INNER JOIN orders o ON u.id = o.user_id
INNER JOIN products p ON o.product_id = p.id
INNER JOIN categories c ON p.category_id = c.id
WHERE o.amount > 100
ORDER BY o.created_at DESC;
-- ============================================
-- SELF JOIN: ๊ฐ์ ํ
์ด๋ธ์ ์๊ธฐ ์์ ๊ณผ ์กฐ์ธ
-- ============================================
-- employees: id, name, manager_id
SELECT
e.name AS employee_name,
m.name AS manager_name
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.id;
-- ๊ฒฐ๊ณผ: ์ง์๊ณผ ๊ทธ ์ง์์ ๋งค๋์ ์ด๋ฆ์ ํจ๊ป ์กฐํ
-- ============================================
-- ์ง๊ณ์ ํจ๊ป ์ฌ์ฉํ๋ JOIN
-- ============================================
SELECT
u.name,
COUNT(o.id) AS order_count,
SUM(o.amount) AS total_spent,
AVG(o.amount) AS avg_order_amount
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
GROUP BY u.id, u.name
HAVING COUNT(o.id) >= 5
ORDER BY total_spent DESC;
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey, func
from sqlalchemy.orm import declarative_base, relationship, Session, joinedload
from sqlalchemy import select
Base = declarative_base()
# ๋ชจ๋ธ ์ ์
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String(100))
email = Column(String(255))
orders = relationship("Order", back_populates="user")
class Order(Base):
__tablename__ = 'orders'
id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey('users.id'))
product_name = Column(String(255))
amount = Column(Integer)
user = relationship("User", back_populates="orders")
# ๋ฐ์ดํฐ๋ฒ ์ด์ค ์ฐ๊ฒฐ
engine = create_engine("postgresql://user:pass@localhost/mydb")
with Session(engine) as session:
# ================================
# 1. ๊ธฐ๋ณธ INNER JOIN
# ================================
stmt = (
select(User.name, Order.product_name, Order.amount)
.join(Order, User.id == Order.user_id)
.where(Order.amount > 100)
)
results = session.execute(stmt).all()
for name, product, amount in results:
print(f"{name}: {product} - {amount}์")
# ================================
# 2. LEFT OUTER JOIN
# ================================
stmt = (
select(User.name, Order.product_name)
.outerjoin(Order, User.id == Order.user_id) # LEFT JOIN
)
results = session.execute(stmt).all()
for name, product in results:
product = product or "์ฃผ๋ฌธ ์์"
print(f"{name}: {product}")
# ================================
# 3. Eager Loading์ผ๋ก N+1 ๋ฌธ์ ํด๊ฒฐ
# ================================
# joinedload: ํ ๋ฒ์ JOIN ์ฟผ๋ฆฌ๋ก ๊ด๋ จ ๋ฐ์ดํฐ๋ฅผ ๊ฐ์ ธ์ด
stmt = (
select(User)
.options(joinedload(User.orders))
.where(User.name.like('๊น%'))
)
users = session.scalars(stmt).unique().all()
for user in users:
print(f"{user.name}์ ์ฃผ๋ฌธ:")
for order in user.orders: # ์ถ๊ฐ ์ฟผ๋ฆฌ ๋ฐ์ํ์ง ์์
print(f" - {order.product_name}")
# ================================
# 4. ์ง๊ณ ํจ์์ GROUP BY
# ================================
stmt = (
select(
User.name,
func.count(Order.id).label('order_count'),
func.sum(Order.amount).label('total_spent')
)
.outerjoin(Order)
.group_by(User.id, User.name)
.having(func.count(Order.id) >= 3)
.order_by(func.sum(Order.amount).desc())
)
results = session.execute(stmt).all()
for name, count, total in results:
print(f"{name}: {count}๊ฑด, ์ด {total or 0:,}์")
# ================================
# 5. ์๋ธ์ฟผ๋ฆฌ๋ฅผ ํ์ฉํ ๋ณต์กํ JOIN
# ================================
# ์ต๊ทผ ์ฃผ๋ฌธ์ด ์๋ ์ฌ์ฉ์๋ง ์กฐํ
subquery = (
select(Order.user_id)
.where(Order.created_at >= '2024-01-01')
.distinct()
.subquery()
)
stmt = (
select(User)
.join(subquery, User.id == subquery.c.user_id)
)
active_users = session.scalars(stmt).all()
Take a mock interview on this topic โ WIA SOOM AI Interview ยท Start for free