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)
            )
相关推荐
这个DBA有点耶17 小时前
SQL中的窗口函数进阶:滑动窗口与帧子句详解
数据库·sql·程序人生·mysql·oracle·学习方法·改行学it
tongyiixiaohuang17 小时前
跨平台数据库集成:SQLServer到MySQL的最佳实践
数据库·mysql·sqlserver
Undergoer_TW17 小时前
Colmap 进军嵌入式:SQLite 数据库从崩溃退出到自动治愈
jvm·数据库·sqlite
徐sir(徐慧阳)17 小时前
记一次麒麟 oracle 12c RAC安装迁移全过程
数据库·oracle
Mr. zhihao17 小时前
Redis 脑裂深度解析:Sentinel 与 Cluster 机制、流程及对比
数据库·redis·sentinel
努力攻坚操作系统17 小时前
MySQL 原理解析
数据库·mysql
数据库小学妹17 小时前
MySQL 字符集深度解析:utf8 vs utf8mb4 的底层差异与索引失效根因
数据库·经验分享·mysql
Daydream.V17 小时前
深入拆解 MySQL 锁机制:全局锁、表级锁、行级锁实战全解析
数据库·mysql·oracle·
小辰记事本17 小时前
从零读懂RDMA硬件排障:读数、看码、查计数器
运维·网络·数据库
JZC_xiaozhong18 小时前
企业微信集成OA、ERP与第三方应用:从“数据孤岛”到“流程闭环”
大数据·数据库·企业微信·etl工程师·持续集成·企业数据安全·数据集成与应用集成