欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

mysql自联去重的一些笔记记录

程序员文章站 2023-11-30 12:22:10
我先把功能场景简要阐述下: 数据行字段如下: name started_at type 在这张表里,name有重复值 现在需要在type确定...

我先把功能场景简要阐述下:

数据行字段如下:

name
started_at
type

在这张表里,name有重复值

现在需要在type确定的情况下,筛选出一个列表,满足,name不重复,找出的记录为同name下started_at为最小的记录

举个例子:

活动1 2019-06-01 type1
活动1 2019-06-02 type1
活动1 2019-06-03 type1

活动2 2019-06-03 type1
活动2 2019-06-05 type1
活动2 2019-06-07 type1

那筛的列表应为:

活动1 2019-06-01 type1
活动2 2019-06-03 type1

还需要满足started_at 大于 当前时间

请问这样的sql应该如何写?

解决思路为:

就是利用left join 自己

比如s1 left join s2 on s1.name=s2.name and s2.started_at<s1.started_at and s2.started_at > now()

最后where s2.id is null

select
 s1.name,
 s1.started_at,
 
from
 tbl s1
 left join tbl s2 on s1.`name` = s2.`name` 
  and s1.started_at > s2.started_at 
  and s2.started_at > now( ) 
where
  s2.id is null 
  and s1.started_at > now( ) 
 and s1.type = 'online_lecture'
order by
 s1.name,
 s1.started_at;

大家有什么更好的解决思路吗?

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。