我有以下疑问:
SELECT u.first_name, o.created_atFROM user AS uINNER JOIN order AS o ON o.user_id = u.idGROUP BY u.id
数据结构如下:
user 1
order 1
order 2
order 3
user 2
order 1
user 3
order 1order 2
user 4
order 1order 2order 3order 4order 5user 1
当前查询返回的数据如下:
>order 1user 2
>order 1user 3
>order 1user 4
>order 1user 1
但我希望用户订单的所有最后项目,如下所示:
>order 3user 2
>order 1user 3
>order 2user 4
>order 5
有没有办法把这个弄得很好?
我需要检索每个用户生成报告的最后一个顺序。

最佳答案

尝试此查询:-

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

用于get MAXSELECT MAX(o2.created_at)

关于mysql - 在MySQL中按desc排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34062936/

10-09 20:40