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)
            )
相关推荐
DemonAvenger4 小时前
NoSQL与MySQL混合架构设计:从入门到实战的最佳实践
数据库·mysql·性能优化
AAA修煤气灶刘哥15 小时前
后端人速藏!数据库PD建模避坑指南
数据库·后端·mysql
RestCloud20 小时前
揭秘 CDC 技术:让数据库同步快人一步
数据库·api
得物技术1 天前
MySQL单表为何别超2000万行?揭秘B+树与16KB页的生死博弈|得物技术
数据库·后端·mysql
可涵不会debug1 天前
【IoTDB】时序数据库选型指南:工业大数据场景下的技术突围
数据库·时序数据库
ByteBlossom1 天前
MySQL 面试场景题之如何处理 BLOB 和CLOB 数据类型?
数据库·mysql·面试
麦兜*1 天前
MongoDB Atlas 云数据库实战:从零搭建全球多节点集群
java·数据库·spring boot·mongodb·spring·spring cloud
Slaughter信仰1 天前
深入理解Java虚拟机:JVM高级特性与最佳实践(第3版)第十章知识点问答(10题)
java·jvm·数据库
麦兜*1 天前
MongoDB 在物联网(IoT)中的应用:海量时序数据处理方案
java·数据库·spring boot·物联网·mongodb·spring