exists在sql中的妙用

最近有两处功能都用到了exists, 觉得它很好地用子查询的方式实现了对主表数据的过滤

1. 支持历史记录id查询主id

那就用子查询过滤一下,主记录对应的历史记录中要存在当前id

sql 复制代码
        <if test="!searchHistoryFlag">
            and cbi.is_last_submit = 1
            <if test="searchSubmitId != null and searchSubmitId != ''">
                and exists (
                    select
                        1
                    from
                        bendcompete_info t
                    where
                        t.vendor_id = cbi.vendor_id
                        and t.submit_user_mobile = cbi.submit_user_mobile
                        and t.submit_year = cbi.submit_year
                        and t.submit_month = cbi.submit_month
                        and t.submit_id = #{searchSubmitId}
                )
            </if>
        </if>
        <if test="searchHistoryFlag">
            <if test="searchSubmitId != null and searchSubmitId != ''">
                and cbi.submit_id = #{searchSubmitId}
            </if>
        </if>

2. 相同会员品牌下取最新月的数据

由于年和月是分开存储的,为了比较月份谁大谁小,那就把年乘以12跟月份相加,统一按月份进行比较

月份可以理解为12进制的数据

sql 复制代码
        select rc.* 
        from  bendcompete_prize_receive_config rc
        where rc.prize_status = 1
           and not exists (
                select
                    1
                from
                    bendcompete_prize_receive_config rc2
                where
                    rc2.member_brand_id = rc.member_brand_id
                    and rc2.submit_year * 12 + rc2.submit_month > (rc.submit_year * 12 + rc.submit_month)
            )
相关推荐
zzzll111122 分钟前
用 DeepSeek Harness 手搓一个自己的 Agent
数据库
名字还没想好☜28 分钟前
Spring @EventListener 事件驱动解耦实战:同步转异步、事务绑定与顺序控制
java·数据库·后端·python·spring
del31 分钟前
第十周技术博客
数据库
1314lay_100741 分钟前
C#调用Sql Server存储过程,并且使用传入表结构
数据库·经验分享·笔记·sqlserver·c#
anxiao_m1 小时前
2026大文件传输软件推荐,从速度安全多维度客观测评
数据库·文件传输·传输
IT大白鼠1 小时前
MySQL 分布式集群系列 · 第七篇——生产调优实战:NDB 性能、内存、高可用全方位优化
数据库·分布式·mysql
IvorySQL1 小时前
打造下一代 AI Agent 的统一多模智能数据底座——PostgreSQL 与 AI 的融合演进
数据库·人工智能·postgresql
ShineWinsu1 小时前
对于MySQL:内置函数的解析
linux·数据库·c++·mysql·面试·函数·查询
isNotNullX1 小时前
智能问数为什么答不准?数据、语义、模型、SQL四层拆解
数据库
烂蜻蜓3 小时前
Django入门教程(三):django-admin与manage.py命令完全指南
数据库·django·sqlite