My tables are: t1(name, date, sold); t2(name, date, bought);
My query is:
SELECT *
FROM (SELECT * FROM t1
UNION ALL
SELECT * FROM t2) AS tRes
WHERE
date < DATE_ADD( DATE_ADD( (SELECT MAX(date) FROM tRes), INTERVAL -DAY((SELECT MAX(date) FROM tRes)) + 1 DAY), INTERVAL -2 MONTH );
I.e. I'm trying to receive rows with dates which are less on two months than max date in tRes - when 2007-12-03 is the max date in the union, the result dates should be less than 2007-10-01.
I'm getting an error 'tRes does not exist' (1146). It's simplified version of the query, in fact there's a lot of code in tRes declaration so I cannot just copy the declaration in selects's below. What can I do here? I want to declare alias of the union which is visible in 'WHERE' clause.