This is a conservative extension if we consider each comma in a list of table_reference
items as equivalent to an inner join. For example:
SELECT * FROM t1 LEFT JOIN (t2, t3, t4) ON (t2.a=t1.a AND t3.b=t1.b AND t4.c=t1.c)
is equivalent to:
SELECT * FROM t1 LEFT JOIN (t2 CROSS JOIN t3 CROSS JOIN t4) ON (t2.a=t1.a AND t3.b=t1.b AND t4.c=t1.c)
In MySQL, JOIN
, CROSS JOIN
, and INNER JOIN
are syntactic equivalents (they can replace each other). In standard SQL, they are not equivalent. INNER JOIN
is used with an ON
clause, CROSS JOIN
is used otherwise.
MySQL also supports nested joins (see Section 8.2.1.9, “Nested Join Optimization”).
A table_subquery
is also known as a subquery in the FROM
clause. Such subqueries must include an alias to give the subquery result a table name. A trivial example follows; see also Section 13.2.10.8, “Subqueries in the FROM Clause”.
-
INNER JOIN
and,
(comma) are semantically equivalent in the absence of a join condition: both produce a Cartesian product between the specified tables (that is, each and every row in the first table is joined to each and every row in the second table).However, the precedence of the comma operator is less than of
INNER JOIN
,CROSS JOIN
,LEFT JOIN
, and so on. If you mix comma joins with the other join types when there is a join condition, an error of the formUnknown column '
may occur. Information about dealing with this problem is given later in this section.//mysql这么奇葩的? inner join 居然是笛卡尔积!!!!col_name
' in 'on clause'
-
If there is no matching row for the right table in the
ON
orUSING
part in aLEFT JOIN
, a row with all columns set toNULL
is used for the right table. You can use this fact to find rows in a table that have no counterpart in another table:SELECT left_tbl.* FROM left_tbl LEFT JOIN right_tbl ON left_tbl.id = right_tbl.id WHERE right_tbl.id IS NULL;
This example finds all rows in
left_tbl
with anid
value that is not present inright_tbl
(that is, all rows inleft_tbl
with no corresponding row inright_tbl
). This assumes thatright_tbl.id
is declaredNOT NULL
. See Section 8.2.1.7, “LEFT JOIN and RIGHT JOIN Optimization”.//这个例子应该也说明了外链接不合并链接的那个项
CREATE TABLE t1 (i INT, j INT); CREATE TABLE t2 (k INT, j INT); INSERT INTO t1 VALUES(1,1); INSERT INTO t2 VALUES(1,1); SELECT * FROM t1 NATURAL JOIN t2; SELECT * FROM t1 JOIN t2 USING (j);
Now the statements produce this output:
+------+------+------+ | j | i | k | +------+------+------+ | 1 | 1 | 1 | +------+------+------+ +------+------+------+ | j | i | k | +------+------+------+ | 1 | 1 | 1 | +------+------+------+
This change also applies to statements that mix the comma operator with INNER JOIN
, CROSS JOIN
, LEFT JOIN
, and RIGHT JOIN
, all of which now have higher precedence than the comma operator.
mysql join 操作总结:
总的来说 mysql 只有两种 join join 与 left/right join。
其中 using 与on用来表示链接条件,二者区别在 上面文档里面有写。
natural join 等价于 join using() natural left/right join 等价于 left/right join using()
逗号优先级低于join,作用等价于join。
没有join条件的 join等价与笛卡尔积!