MySQL - ORDER BY DESC和GROUP BY

时间:2016-03-09 07:22:39

标签: mysql sql-order-by

我有一个customers表及其字段,例如userId,customerId和created。

这是customers

中的数据
userId    customerId    created
user_1    customer_1    2016-03-04 00:00:00
user_1    customer_2    2016-10-04 00:00:00
user_1    customer_3    2016-07-04 00:00:00
user_1    customer_4    2016-09-04 00:00:00
user_2    customer_5    2016-06-04 00:00:00
user_2    customer_6    2016-03-04 00:00:00

我使用了以下一些查询来获取每个用户的最新信息。这是我试过的一个查询

select *
from customers
order by created desc
group by userId

上述查询无效。我想要的结果是:

user_1    customer_2    2016-10-04 00:00:00
user_2    customer_5    2016-06-04 00:00:00

也许我不清楚order bygroup by命令的工作原理。你能给我一些解决方案吗?

3 个答案:

答案 0 :(得分:1)

SELECT c1.userId, c1.customerId, c1.created
FROM customers c1
INNER JOIN
(
    SELECT userId, MAX(created) AS maxCreated
    FROM customers
    GROUP BY userId
) c2
    ON c1.userId = c2.userId AND c1.created = c2.maxCreated
ORDER BY c1.created

请注意,您不需要在DESC子句中明确使用ORDER BY,因为MySQL默认按降序排序。

答案 1 :(得分:1)

试试这个:

SELECT 
    *
FROM 
    customers c1
WHERE 
    (userId, created) IN 
        (
            SELECT userId, MAX(created)
            FROM customers c2
            WHERE c1.userId = c2.userId
        );

答案 2 :(得分:0)

如果您尝试这样做,您将获得所需的结果:

SELECT * FROM customers WHERE created = (select max(created) from customers a where a.userId = customers.userId )

group by子句允许您获得最大值:

select userId,max(created) from customers group by userId

这样您就可以获得每个userId的最大日期,并在将其放入某些值后将其用于另一个查询。

这样的东西只给你一行最大日期:

select userId,customerId,max(created) from customers order by created desc