多表连接的方式
//from t1, t2 where . . .
SELECT * FROM
t1, t2
WHERE t1.m = t2.m and . . .;
//(inner) join t2 on . . .
SELECT column_name(s) FROM t1
INNER JOIN t2
ON t1.m = t2.m and t1.m = 2 . . .;
//left join t2 on . . .
SELECT column_name(s) FROM t1
LEFT JOIN t2
ON t1.m = t2.m
//right join t2 on . . .
SELECT column_name(s) FROM t1
RIGHT JOIN t2
ON t1.m = t2.m
//full join t2 on . . .
SELECT column_name(s) FROM t1
FULL JOIN t2
ON t1.m = t2.m and . . .
多表连接的原理
对于两个表连接操作,需要区分驱动表和被驱动表:
- 驱动表:第一个需要查询的表,执行查询的策略与普通单表查询一致;
- 被驱动表:针对上一步骤中从驱动表产生的结果集中的每一条记录,需要分别到被驱动表中查找匹配的记录。
在上面的例子中,驱动表和被驱动表分别是:
1) from t1, t2 where . . .
驱动表: t1或t2 被驱动表: t1或t2
2) (inner) join t2 on . . .
驱动表: t1或t2 被驱动表: t1或t2
3) left join t2 on . . .
驱动表: t1 被驱动表: t2
4) right