MySQL - ORDER BY DESC 和 GROUP BY

MySQL - ORDER BY DESC and GROUP BY

我有一个 customers table,其字段包括 userId、customerId 和 created。

这是customerstable

中的数据
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命令的工作原理不是很清楚。你能给我一些解决方案吗?

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

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

试试这个:

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

如果你尝试这样做,你会得到你想要的结果:

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