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)
            )
相关推荐
星辰_mya11 分钟前
InnoDB的“身体结构”:页、Buffer Pool与Redo Log的底层奥秘
数据库·mysql·spring·面试·系统架构
F1FJJ37 分钟前
Shield CLI 命令全解析:15 个命令覆盖所有远程访问场景
网络·数据库·网络协议·容器·开源软件
IMPYLH43 分钟前
Linux 的 dircolors 命令
linux·运维·服务器·数据库
2301_822782821 小时前
自动化与脚本
jvm·数据库·python
qq_148115371 小时前
为你的Python脚本添加图形界面(GUI)
jvm·数据库·python
2401_878530212 小时前
机器学习与人工智能
jvm·数据库·python
tianyuanwo2 小时前
MySQL 深度解析:从核心概念到实战指南,及数据库选型决策
数据库·mysql·centos
代码探秘者2 小时前
【算法】吃透18种Java 算法快速读写模板
数据结构·数据库·python·算法·spring
深蓝轨迹2 小时前
Redis 消息队列
java·数据库·redis·缓存·面试·秒杀
曹牧3 小时前
Oracle:分批查询
数据库·oracle