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)
            )
相关推荐
珊珊而川27 分钟前
MAC-SQL 算法一
数据库·sql·oracle
听风吟丶1 小时前
深入解析 Spring Boot 自动配置:原理、实践与进阶
java·数据库·sql
风语者日志1 小时前
[LitCTF 2023]这是什么?SQL !注一下 !
android·数据库·sql
lang201509281 小时前
Spring Boot 核心技巧与实战指南
java·数据库·spring boot
呆呆小金人2 小时前
SQL视图:虚拟表的完整指南
大数据·数据库·数据仓库·sql·数据库开发·etl·etl工程师
笨手笨脚の2 小时前
Mysql 读书笔记
数据库·mysql·事务·索引·orderby·自增主键
码力引擎2 小时前
【零基础学MySQL】第四章:DDL详解
数据库·mysql·1024程序员节
程序新视界2 小时前
MySQL的隔离级别及其工作原理详解
数据库·后端·mysql
liliangcsdn3 小时前
如何基于llm+mysql构建轻量级全文搜索
数据库·人工智能·mysql
李慕婉学姐3 小时前
Springboot微信小程序在线考试系统w47h61gy(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·微信小程序