I have a table users and a table orders.
The table users has a primary key user_id and some other fields. The table orders has a foreign key user_id, a name order_name and a date order_date.
For a legacy export, I need to build a query that returns the data in the form
user_id | order_name1 | order_name2 | order_name3 where order 1-3 are the three most recent orders of the customers.
My idea is to query on customers and make three joins with select to orders
SELECT
users.*,
order1.order_name AS order_name1,
order2.order_name AS order_name2,
order3.order_name AS order_name3
FROM users AS users
JOIN (
SELECT
user_id,
order_name,
order_date
FROM orders ORDER BY order_date DESC OFFSET 0 LIMIT 1)
AS order1 ON order1.user_id=users.user_id
JOIN (
SELECT
user_id,
order_name,
order_date
FROM orders ORDER BY order_date DESC OFFSET 1 LIMIT 1)
AS order2 ON order2.user_id=users.user_id
JOIN (
SELECT
user_id,
order_name,
order_date
FROM orders ORDER BY order_date DESC OFFSET 2 LIMIT 1)
AS order3 ON order3.user_id=users.user_id
However, this does not work as it only returns one row each from orders, and not specifically for each user.
How to write such a query?