我需要构建可以获取客户最新购买的推进查询
请在您的答案中使用这些表/列名称:
- 客户:身份证、姓名
- 购买:id、customer_id、日期
从这里的这个问题SQL join: selection the last records in a one-to-many relationship
我需要基于以下查询之一构建推进查询:
或者SELECT c.*, p1.* FROM customer c JOIN purchase p1 ON (c.id = p1.customer_id) LEFT OUTER JOIN purchase p2 ON (c.id = p2.customer_id AND (p1.date < p2.date OR p1.date = p2.date AND p1.id < p2.id)) WHERE p2.id IS NULL;
SELECT c.*, p.*
FROM customer c INNER JOIN
(
SELECT customer_id,
MAX(date) MaxDate
FROM purchase
GROUP BY customer_id
) MaxDates ON c.id = MaxDates.customer_id INNER JOIN
purchase p ON MaxDates.customer_id = p.customer_id
AND MaxDates.MaxDate = p.date