Difference between ON and WHERE in subquery

跟風遠走 提交于 2019-12-23 02:41:01

问题


I found a weird disparity in mysql between using an ON and a WHERE to filter a subquery with a join.

This query runs fine:

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
)

But this one returns an error 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
)

Obviously the subquery's ON clause does not have access to to the outer query's alias, while the WHERE claus does. Why is this and can anyone point out where in the documentation this is covered?

EDIT: Removed unneeded background information involving pre-mature optimization.


回答1:


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);

-- MySQL docs, 13.2.9.2 JOIN Syntax




回答2:


The where clause applies to the whole resultset.

The on clause only applies to the join in query.

Please refer following Links

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?



来源:https://stackoverflow.com/questions/35788185/difference-between-on-and-where-in-subquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!