SELECT
t1.customer_id,
c.customer_name,
p.product_name AS latest_order
FROM (
SELECT
customer_id,
MAX(order_date) AS t2
FROM orders
GROUP BY customer_id
) t1
JOIN orders o ON o.customer_id = t1.customer_id AND o.order_date = t1.t2
JOIN customers c ON o.customer_id = c.customer_id
JOIN products p ON p.product_id = o.product_id
ORDER BY t1.customer_id;
--T1 只告诉你 “某个客户最后一次下单是哪一天”,但不告诉你 “那一天他买了什么商品”,而 orders 表才存储了「客户 ID、下单日期、商品 ID」的对应关系,因此必须关联 orders 表。



京公网安备 11010502036488号