不考虑性能,我会从下面的查询 A 和 B 中得到相同的结果吗?C和D怎么样?
-- A select * from a left join b on <blahblah> left join c on <blahblan> -- B select * from a left join c on <blahblah> left join b on <blahblan> -- C select * from a join b on <blahblah> join c on <blahblan> -- D select * from a join c on <blahblah> join b on <blahblan>
对于INNER连接,不,顺序无关紧要。只要您将选择从 更改为 ,查询将返回相同的SELECT *结果SELECT a.*, b.*, c.*。
INNER
SELECT *
SELECT a.*, b.*, c.*
对于 ( LEFT, RIGHTor FULL)OUTER连接,是的,顺序很重要 - 而 ( 更新 ) 事情要复杂得多。
LEFT
RIGHT
FULL
OUTER
首先,外连接不是可交换的,所以a LEFT JOIN b不等同于b LEFT JOIN a
a LEFT JOIN b
b LEFT JOIN a
外连接也不具有关联性,因此在您的示例中同时涉及(交换性和关联性)属性:
a LEFT JOIN b ON b.ab_id = a.ab_id LEFT JOIN c ON c.ac_id = a.ac_id
相当于 :
a LEFT JOIN c ON c.ac_id = a.ac_id LEFT JOIN b ON b.ab_id = a.ab_id
但:
a LEFT JOIN b ON b.ab_id = a.ab_id LEFT JOIN c ON c.ac_id = a.ac_id AND c.bc_id = b.bc_id
不等于 :
a LEFT JOIN c ON c.ac_id = a.ac_id LEFT JOIN b ON b.ab_id = a.ab_id AND b.bc_id = c.bc_id
另一个(希望更简单)关联性示例。将其视为(a LEFT JOIN b) LEFT JOIN c:
(a LEFT JOIN b) LEFT JOIN c
a LEFT JOIN b ON b.ab_id = a.ab_id -- AB condition LEFT JOIN c ON c.bc_id = b.bc_id -- BC condition
这 相当于a LEFT JOIN (b LEFT JOIN c):_
a LEFT JOIN (b LEFT JOIN c)
a LEFT JOIN b LEFT JOIN c ON c.bc_id = b.bc_id -- BC condition ON b.ab_id = a.ab_id -- AB condition
只是因为我们有“好”的ON条件。ON b.ab_id = a.ab_id和都是c.bc_id = b.bc_id相等检查,不涉及NULL比较。
ON
ON b.ab_id = a.ab_id
c.bc_id = b.bc_id
NULL
您甚至可以使用其他运算符或更复杂的运算符来设置条件,例如:ON a.x <= b.xorON a.x = 7或ON a.x LIKE b.xorON (a.x, a.y) = (b.x, b.y)并且这两个查询仍然是等效的。
ON a.x <= b.x
ON a.x = 7
ON a.x LIKE b.x
ON (a.x, a.y) = (b.x, b.y)
但是,如果涉及其中任何IS NULL一个或与空值相关的函数,COALESCE()例如,如果条件是b.ab_id IS NULL,那么这两个查询将不等价。
IS NULL
COALESCE()
b.ab_id IS NULL