简体   繁体   English

MySQL-按DESC排序和按GROUP BY

[英]MySQL - ORDER BY DESC and GROUP BY

I have a customers table with its field such as userId, customerId and created. 我有一个customers表及其字段,如userId,customerId和已创建。

This is the data in customers table 这是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

I used some following queries to get latest created of each user. 我使用以下一些查询来获取每个用户的最新创建信息。 And this is one of queries I tried 这是我尝试过的查询之一

select *
from customers
order by created desc
group by userId

The above query didn't work properly. 上面的查询无法正常工作。 My desired result is: 我想要的结果是:

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

Maybe I don't understand clearly about how order by and group by commands work. 也许我不太了解order bygroup by工作方式。 Could you give me some solutions? 你能给我一些解决方案吗?

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

Note that you don't need to explicitly use DESC with the ORDER BY clause, because MySQL sorts in descending order by default. 注意,您不需要在ORDER BY子句中显式使用DESC ,因为MySQL默认情况下按降序排序。

Try this: 尝试这个:

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

If you try do in this way, you'll get the result you want: 如果尝试以这种方式执行操作,则将获得所需的结果:

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

group by clause allows you get maximum value: group by子句可让您获得最大价值:

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

so that you get max date for each userId and after putting it into some values you can use in the another query. 这样您可以获得每个userId的最大日期,并将其放入某些值后可以在另一个查询中使用。

Something like that gives you only one row with maximum date: 这样的事情只给您一行具有最大日期的信息:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM