我有以下查询:
SELECT u.first_name, o.created_at
FROM user AS u
INNER JOIN order AS o ON o.user_id = u.id
GROUP BY u.id
数据结构如下所示:
user 1
order 1
order 2
order 3
user 2
order 1
user 3
order 1
order 2
user 4
order 1
order 2
order 3
order 4
order 5
目前查询返回的数据如下:
user 1
>
order 1
user 2
>
order 1
user 3
>
order 1
user 4
>
order 1
但我想拥有用户订单的所有最后一项,如下例所示:
user 1
>
order 3
user 2
>
order 1
user 3
>
order 2
user 4
>
order 5
有没有办法很好地解决这个问题? 我需要检索每个用户的最后一个订单以生成报告。
答案 0 :(得分:1)
尝试此查询: -
SELECT u.first_name, o.created_at
FROM user AS u
INNER JOIN order AS o ON o.user_id = u.id
Where o.created_at=(SELECT MAX(o2.created_at)
FROM order o2
WHERE o.user_id = o2.user_id);
GROUP BY u.id
此SELECT MAX(o2.created_at)
用于获取MAX created_at
答案 1 :(得分:0)
SELECT u.first_name, max(o.created_at) as max_created_at
FROM user u
INNER JOIN order AS o ON o.user_id = u.id
GROUP BY u.id