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)
            )
相关推荐
····懂···37 分钟前
攻克PostgreSQL专家认证
数据库·postgresql
每天都在想吃啥1 小时前
day31 SQLITE
数据库·sqlite
m0_748254094 小时前
2025最新华为云国际版注册图文流程-不用绑定海外信用卡注册
服务器·数据库·华为云
大新屋4 小时前
MongoDB 分片集群修改管理员密码
数据库·mongodb
ejinxian4 小时前
MySQL/Kafka数据集成同步,增量同步及全量同步
数据库·mysql·kafka
未来之窗软件服务4 小时前
数据库优化提速(一)之进销存库存管理—仙盟创梦IDE
数据库·sql·数据库调优
Mapmost5 小时前
信创浪潮下的GIS技术变革:从自主可控到生态繁荣
数据库
foundbug9995 小时前
Node.js导入MongoDB具体操作
数据库·mongodb·node.js
天天进步20155 小时前
Node.js中的Prisma应用:现代数据库开发的最佳实践
数据库·node.js·数据库开发
hui函数6 小时前
Flask高效数据库操作指南
数据库·python·flask