mysql - How to apply intersection grouped with index column in MYSQL
问题描述
I have a dataset of logged in users on a certain date
__ds__|__user_id__
1 | 1
1 | 2
2 | 2
2 | 3
3 | 3
3 | 1
3 | 2
i want to perform intersection on user_id over two consecutive dates, to have users who logged in today as well as previous day, so my final out put will be:
__ds__|__user_id__
2 | 2
3 | 3
3 | 2
I have wrote a query as:
select distinct t1.ds,t1.user_id
from user_table t1
where t1.user_id in(
select distinct user_id
from user_table
where ds = t1.ds-1
)
I applied distinct two time, which took too long time to run on big dataset. Is there more optimized way?
解决方案
我觉得可以是这样
select t2.ds,t2.user_id
from user_table t1
join user_table t2 on t1.user_id=t2.user_id and t2.ds=t1.ds+1
对不对?
推荐阅读
- excel - 运行时错误 5 - 无效的过程调用或参数 - 保存 Word 文档时
- python - 图未在 python tkinter gui 中显示
- reactjs - 如何在功能组件之间传递状态?
- conditional-statements - 条件不编译并产生错误
- flutter - 添加容器颜色时出错:ParentDataWidget 的使用不正确
- arrays - 如何将作为字符串数组的单元格内容作为参数传递给函数?
- google-sheets - 处理数据时,谷歌表格导入不会改变单元格值
- laravel - E: 使用 docker compose 在 php-fpm 映像构建中,包 'mysql-client' 没有安装候选
- swift - 使用 AVCaptureVideoDataOutput 正确录制视频
- java - Tomcat webclassloader 找不到类