如何更改 MySQL 分组前的顺序?

How do I change the order before MySQL grouping?

如果table中有超过1个相同的号码,我只带一个。但在带来之前,第一个添加的日期来自记录。我想要最后添加的记录。

这是一个例子;

SELECT * FROM comments WHERE phone_number='01234'

输出:

id | phone | created_at
-----------------------
1   01234   2020-10-27
2   01234   2020-10-28

MySQL代码;

SELECT * FROM comments GROUP BY phone_number ORDER BY created_at DESC

MySQL输出;

id | phone | created_at
-----------------------
1   01234   2020-10-27

如果您想要最近的 ,则不需要聚合。相反,过滤它:

select c.*
from c
where c.created_at = (select max(c2.created_at)
                      from comments c2
                      where c2.phone = c.phone
                     );

或使用window函数:

select c.*
from (select c.*,
             row_number() over (partition by phone order by created_at desc) as seqnum
      from comments c
     ) c
where seqnum = 1;

或者,如果您只想要一个 phone,那么您可以使用 order bylimit:

select c.*
from c
where phone = '3244003390'
order by c.created_at desc
limit 1;

从 MySQL 8.0 开始,您可以使用 window 函数来达到此目的:

select * from (
  select 
      comments.*,
      row_number() over (partition by phone order by created_at desc) row_num
  from comments
) c where row_num = 1;

SQLize.online

上测试

以防万一 created_at 列与 id 相关,您可以使用下一个方法:

select 
    max(id) id,
    phone,
    max(created_at) created_at
from comments
group by phone;

它 returns 每个 phone 的最后 id 和最后 created_at 值,并且适用于旧的 MySQL 版本。

SQLize.online

沿着这条线,使用 id 因为它更快而且没有真正的理由使用 created_at:

SELECT t.*  FROM  comments t 
        WHERE t.id = (SELECT MAX(t2.id) FROM comments t2
        WHERE t2.phone = t.phone)