左连接
返回左表(即主表)中的所有记录,即使右表中没有匹配的记录,也会返回左表的数据,并将右表对应的字段设置为
NULL。
SQL
select FirstName, LastName, City, State
from Person left join Address
on Person.personId = Address.personId隐式连接
当 FROM 子句中列出多个表(这里是同一个表的两个别名)而没有明确使用 JOIN 关键字时,数据库会默认执行隐式连接,生成两个表所有行的组合(笛卡尔积) 假设你的表有这两行数据:
| id | name | salary | managerId |
|---|---|---|---|
| 1 | Joe | 70000 | 3 |
| 2 | Henry | 80000 | 4 |
| 3 | Sam | 60000 | NULL |
| 4 | Max | 90000 | NULL |
笛卡尔积后的部分结果(假设 a 是员工,b 是经理)会是:
| a.id | a.name | a.salary | a.managerId | b.id | b.name | b.salary | b.managerId |
|---|---|---|---|---|---|---|---|
| 1 | Joe | 70000 | 3 | 3 | Sam | 60000 | NULL |
| 1 | Joe | 70000 | 3 | 4 | Max | 90000 | NULL |
| 这种方法会产生大量不必要数据,存在性能问题,且语义不清晰。 |
内连接
只返回两个表中匹配连接条件的记录。如果某行在两个表中没有匹配项,它就不会出现在结果中.
SQL
SELECT
a.name AS Employee
FROM
Employee AS a
JOIN
Employee AS b
ON
a.ManagerId = b.Id
AND a.Salary > b.Salary;连接条件使用 ON,过滤结果集使用 WHERE。