Bài 3
Home

JOIN nhiều bảng

Kết hợp dữ liệu từ nhiều bảng với JOIN

TargetMục tiêu học tập

  • Hiểu khi nào cần JOIN
  • Phân biệt INNER JOIN và LEFT JOIN
  • Kết hợp dữ liệu từ 2-3 bảng

Lesson 3: JOIN Nhiều Bảng

Tại sao cần JOIN?

  • Bảng products chỉ có category_id
  • Tên category thực sự nằm trong bảng categories

INNER JOIN

SELECT p.product_name, c.category_name
FROM products p
INNER JOIN categories c ON p.category_id = c.category_id;

LEFT JOIN

SELECT s.sale_date, c.customer_name, s.total_amount
FROM sales s
LEFT JOIN customers c ON s.customer_id = c.customer_id;

JOIN nhiều bảng

SELECT 
  s.sale_date,
  st.store_name,
  p.product_name,
  c.customer_name,
  s.total_amount
FROM sales s
INNER JOIN stores st ON s.store_id = st.store_id
INNER JOIN products p ON s.product_id = p.product_id
LEFT JOIN customers c ON s.customer_id = c.customer_id
LIMIT 20;
Home

SQL Editor

Loading...
Clipboard

Bài tập thực hành

Bài tập 1: Lấy danh sách sản phẩm kèm tên category và brand

HintGợi ý

JOIN bảng products với categories

CheckXem đáp án
SELECT p.product_name, c.category_name, p.brand
FROM products p
INNER JOIN categories c ON p.category_id = c.category_id;

Bài tập 2: Lấy 10 giao dịch bán hàng kèm tên sản phẩm và tên cửa hàng

HintGợi ý

JOIN sales với products và stores

CheckXem đáp án
SELECT s.sale_date, p.product_name, st.store_name, s.total_amount
FROM sales s
INNER JOIN products p ON s.product_id = p.product_id
INNER JOIN stores st ON s.store_id = st.store_id
LIMIT 10;

Bài tập 3: Lấy giao dịch có thông tin khách hàng (bao gồm cả khách vãng lai)

HintGợi ý

Dùng LEFT JOIN với customers

CheckXem đáp án
SELECT s.sale_date, c.customer_name, s.total_amount
FROM sales s
LEFT JOIN customers c ON s.customer_id = c.customer_id
LIMIT 20;
HomeTrang chủ

Đang tải schema...

Bài 3: JOIN nhiều bảng - Học SQL | Data Bình Dân