The reason for the error is in the MySQL manual :
INNER JOIN
and ,
(comma) are semantically equivalent in the absence of a join condition: both produces 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 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 form Unknown column 'col_name' in 'on clause' may occur.
(...)
Now JOIN
has higher precedence, so the expression is interpreted as (t1, (t2 JOIN t3))
.
That is, mixing an implicit join (with commas) with other explicit joins ( INNER
, LEFT
, etc.) can cause problems because the precedence of the comma is less than the explicit joins.
In the case of your query, joins are interpreted as (P, (T LEFT JOIN PP ON...))
, and this does not make sense, because its condition in ON
does not associate T
to PP
, but P
a PP
.
The solution is simple, just use an explicit join:
SELECT @ROW_NUMBER:=@ROW_NUMBER+1 AS ROW_NUMBER,
P.PEDIDOID
FROM PEDIDO AS P
INNER JOIN (SELECT @ROW_NUMBER:=0) AS T
LEFT JOIN PEDIDOPRODUTO AS PP ON PP.PEDIDOID = P.PEDIDOID
ORDER BY P.PEDIDOID DESC;