子查询中ON和WHERE的区别
Difference between ON and WHERE in subquery
我发现 mysql 在使用 ON 和 WHERE 过滤带连接的子查询之间存在奇怪的差异。
此查询运行良好:
SELECT * FROM cobrand co WHERE co.id IN (
SELECT co2.id FROM cobrand co3 INNER JOIN cobrand co2
ON co2.id = co3.id + 1
WHERE co2.id = co.id
)
但是这个returns一个错误Unknown column 'co.id' in 'on clause'
:
SELECT * FROM cobrand co WHERE co.id IN (
SELECT co2.id FROM cobrand co3 INNER JOIN cobrand co2
ON co2.id = co3.id + 1
AND co2.id = co.id
)
显然,子查询的 ON 子句无法访问外部查询的别名,而 WHERE 子句可以。为什么会这样,谁能指出文档中的哪些地方涵盖了这一点?
编辑:删除了不需要的涉及过早优化的背景信息。
Previously, the ON clause could refer to columns in tables named to
its right. Now an ON clause can refer only to its operands.
Example:
CREATE TABLE t1 (i1 INT);
CREATE TABLE t2 (i2 INT);
CREATE TABLE t3 (i3 INT);
SELECT * FROM t1 JOIN t2 ON (i1 = i3) JOIN t3;
Previously, the SELECT statement was legal. Now the statement fails
with an Unknown column 'i3' in 'on clause' error because i3 is a
column in t3, which is not an operand of the ON clause. The statement
should be rewritten as follows:
SELECT * FROM t1 JOIN t2 JOIN t3 ON (i1 = i3);
The where clause applies to the whole resultset.
The on clause only applies to the join in query.
请参考以下链接
What's the difference between where clause and on clause when table left join?
In SQL / MySQL, what is the difference between "ON" and "WHERE" in a join statement?
我发现 mysql 在使用 ON 和 WHERE 过滤带连接的子查询之间存在奇怪的差异。
此查询运行良好:
SELECT * FROM cobrand co WHERE co.id IN (
SELECT co2.id FROM cobrand co3 INNER JOIN cobrand co2
ON co2.id = co3.id + 1
WHERE co2.id = co.id
)
但是这个returns一个错误Unknown column 'co.id' in 'on clause'
:
SELECT * FROM cobrand co WHERE co.id IN (
SELECT co2.id FROM cobrand co3 INNER JOIN cobrand co2
ON co2.id = co3.id + 1
AND co2.id = co.id
)
显然,子查询的 ON 子句无法访问外部查询的别名,而 WHERE 子句可以。为什么会这样,谁能指出文档中的哪些地方涵盖了这一点?
编辑:删除了不需要的涉及过早优化的背景信息。
Previously, the ON clause could refer to columns in tables named to its right. Now an ON clause can refer only to its operands.
Example:
CREATE TABLE t1 (i1 INT); CREATE TABLE t2 (i2 INT); CREATE TABLE t3 (i3 INT); SELECT * FROM t1 JOIN t2 ON (i1 = i3) JOIN t3;
Previously, the SELECT statement was legal. Now the statement fails with an Unknown column 'i3' in 'on clause' error because i3 is a column in t3, which is not an operand of the ON clause. The statement should be rewritten as follows:
SELECT * FROM t1 JOIN t2 JOIN t3 ON (i1 = i3);
The where clause applies to the whole resultset.
The on clause only applies to the join in query.
请参考以下链接
What's the difference between where clause and on clause when table left join?
In SQL / MySQL, what is the difference between "ON" and "WHERE" in a join statement?