kawak2 2022-05-18 18:43 采纳率: 100%
浏览 163
已结题

mysql 怎么查询同一张表的两个时间段内不重复的数据

项目产生数据中保存A张表,表内数据:

img

业务需求按照 时间段 对比 比如:
第一时间段(2022-05-15 00:00:00 至 2022-05-15 23:59:59)之间存在 和 第二时间段(2022-05-16 00:00:00 至 2022-05-16 23:59:59)之间 不存在 即减少数据
第一时间段(2022-05-15 00:00:00 至 2022-05-15 23:59:59)之间不存在 和 第二时间段(2022-05-16 00:00:00 至 2022-05-16 23:59:59)之间 存在 即新增数据

如果数据两个表可以用一下语句实现预期效果:

SELECT * FROM test1 WHERE NOT EXISTS (SELECT 1 FROM test2 where test1.test = test2.test); -- 减少
SELECT * FROM test2 WHERE NOT EXISTS (SELECT 1 FROM test1 where test2.test = test1.test); -- 新增

如:
新增数据:

img

减少数据

img

怎么样一条语句达到预期效果 ? 请大人们帮忙。谢谢!

  • 写回答

3条回答 默认 最新

  • kawak2 2022-05-18 22:37
    关注
    select *,'减少' as type from test1 befores where (dates >= '2022-05-15 00:00:00' and dates <= '2022-05-15 23:59:59') and not exists (select * from test1 afters where (dates >= '2022-05-16 00:00:00' and dates <= '2022-05-16 23:59:59') and befores.test = afters.test) union all
    select *,'新增' as type from test1 afters where (dates >= '2022-05-16 00:00:00' and dates <= '2022-05-16 23:59:59') and not exists (select * from test1 befores where (dates >= '2022-05-15 00:00:00' and dates <= '2022-05-15 23:59:59') and afters.test = befores.test);
    

    最终按此SQL语句实现想要的效果。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 5月26日
  • 已采纳回答 5月18日
  • 修改了问题 5月18日
  • 创建了问题 5月18日