Here is an oddity I cannot explain:
FROM (
SELECT @report_date :=
IF (DAYOFWEEK(CURDATE()) BETWEEN 3 AND 7, DATE_SUB(CURDATE(), INTERVAL 1 DAY),
IF (DAYOFWEEK(CURDATE()) = 1, DATE_SUB(CURDATE(), INTERVAL 2 DAY),
IF (DAYOFWEEK(CURDATE()) = 2, DATE_SUB(CURDATE(), INTERVAL 3 DAY), NULL)))
) AS dt
, t1
LEFT JOIN t2 ON t1.id = t2.id
http://sqlfiddle.com/#!2/9e0c4/3
Works.
FROM t1
, (
SELECT @report_date :=
IF (DAYOFWEEK(CURDATE()) BETWEEN 3 AND 7, DATE_SUB(CURDATE(), INTERVAL 1 DAY),
IF (DAYOFWEEK(CURDATE()) = 1, DATE_SUB(CURDATE(), INTERVAL 2 DAY),
IF (DAYOFWEEK(CURDATE()) = 2, DATE_SUB(CURDATE(), INTERVAL 3 DAY), NULL)))
) AS dt
LEFT JOIN t2 ON t1.id = t2.id
http://sqlfiddle.com/#!2/9e0c4/2
Doesn't work, error:
Unknown column 't1.id' in 'on clause': ...
Why? Note the order of where t1
is declared in the FROM
clause.
Note, I'm not necessarily looking for alternatives, I would simply like to understand why the order here causes an error on a JOIN
that I would have thought would occur following when the FROM
clause is completed.
If someone were interested in how I ended up here, see this broken fiddle and this working fiddle for a basic example of the real query.