mysql自联去重的一些笔记记录
程序员文章站
2024-01-27 21:22:52
我先把功能场景简要阐述下:
数据行字段如下:
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;
大家有什么更好的解决思路吗?
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。
上一篇: C#检测DataSet是否为空的方法
下一篇: 跟老齐学Python之开始真正编程