JOIN 根据相关列组合来自多个表的行——是查询分散在表中的关系数据的必要条件。当没有匹配时,联接类型决定保留哪些行。
设置
sql
-- two related tables: users and their orders (orders.user_id → users.id)
SELECT users.name, orders.total
FROM users
JOIN orders users.id orders.user_id;
ON 子句指定表之间的关系(将外键与主键匹配)。联接类型控制不匹配的行会发生什么。
INNER JOIN → only rows that MATCH in BOTH tables (the intersection)
users WITH orders only — users with no orders are excluded
LEFT JOIN → ALL rows from the LEFT table + matches from the right (NULL if no match)
ALL users, with their orders (or NULL for users with no orders)
RIGHT JOIN → ALL rows from the RIGHT table + matches from the left (NULL if no match)
ALL orders, with their user (mirror of LEFT)
FULL JOIN → ALL rows from BOTH tables (matched where possible, NULL where not)
-- INNER — only users who have orders
SELECT u.name, o.total FROM users u INNER JOIN orders o ON u.id = o.user_id;
-- LEFT — ALL users, even those with no orders (o.total is NULL for them)
SELECT u.name, o.total FROM users u LEFT JOIN orders o ON u.id = o.user_id;
-- LEFT JOIN + IS NULL → users who have NEVER ordered
SELECT u.name
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
WHERE o.id IS NULL; -- no matching order → o.id is NULL
LEFT JOIN + IS NULL 模式查找一个表中在另一个表中没有对应行的行——这是一种非常常见且有用的技术。
INNER → A ∩ B (matches only)
LEFT → all A + matching B
RIGHT → all B + matching A
FULL → all A + all B
JOIN 是关系数据库的基础——数据被故意分散到相关表中(用户、订单、产品),JOIN 是如何在查询中组合相关数据的方式,因此理解它对于几乎任何非平凡的数据库工作都是必不可少的。
理解四种联接类型及其对不匹配行的处理是关键技能:INNER JOIN(仅匹配的行——最常见的),LEFT JOIN(左表的所有行,不匹配时为 NULL——当你需要所有记录而不考虑匹配时至关重要),RIGHT JOIN(镜像),以及 FULL JOIN(来自两个表的所有行)。
选择正确的联接类型直接决定了你的结果——使用 INNER 当你本意是 LEFT 时会静默地删除行(常见的错误),因此理解这种区别对于正确性很重要。
LEFT JOIN + IS NULL 模式(查找在另一个表中没有匹配的行——例如从未下单的用户)是一种特别有用且常见的技术,值得了解。
由于关系数据分散在表中,JOIN 是一起查询的主要方式,而联接类型严重影响结果中出现的行,因此掌握 JOIN——四种类型、它们对不匹配的行为,以及反联接等模式——是 SQL 的核心、经常应用的知识,也是最重要和最常见的测试数据库概念之一。