I am trying to run the following query:
SELECT customers.id, customers.name, o.order_date
FROM customers,
(SELECT id,
order_date
FROM orders ORDER BY order_date DESC) as o
WHERE o.id = (
SELECT id
FROM o
WHERE customer_id = customers.id
LIMIT 1)
ORDER BY customer_id;
However it results with an error
relation "o" does not exist
I understand that there is an issue with an alias of a subquery above it but I don't know how can I fix it. The reason why I'm not referencing "orders" table directly in WHERE clause is because I want to optimise it by creating a subquery with just 2 columns which are ordered, so this query is not executed on entire table each time a comparison in WHERE clause is made (is it how it works?).
Is there any other way I can write this query?