6.3 — 多表连接
你将学习
- 如何在 SQL 中连接三个或更多表
- 与 Excel 中使用多个 VLOOKUP 的比较
- 语法和最佳实践
示例表
表 sales:
SaleID | ProductID | CustomerID | Amount |
---|---|---|---|
1 | 101 | 1001 | 120 |
2 | 102 | 1002 | 80 |
3 | 103 | 1003 | 50 |
表 products:
ProductID | ProductName |
---|---|
101 | Apples |
102 | Oranges |
103 | Bananas |
表 customers:
CustomerID | CustomerName |
---|---|
1001 | John Smith |
1002 | Jane Doe |
1003 | Mike Johnson |
连接多个表
在 Excel 中,您可能会使用多个 VLOOKUP 从不同工作表引入数据。在 SQL 中,您可以连接任意数量的表。
示例:连接销售、产品和客户表
sql
SELECT s.SaleID, s.Amount, p.ProductName, c.CustomerName
FROM sales s
INNER JOIN products p
ON s.ProductID = p.ProductID
INNER JOIN customers c
ON s.CustomerID = c.CustomerID;
- 每个
JOIN
都会向结果中添加另一个表 - 使用表别名(
s
,p
,c
)提高可读性
关键要点
- 只要定义了关系,您可以连接任意数量的表
- 使用清晰的别名保持查询可读性
下一步
接下来,您将学习如何将 Excel 工作流迁移到 SQL,以实现更高效、可扩展的分析