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)
            )
相关推荐
章鱼哥7309 分钟前
[特殊字符] SpringBoot 自定义系统健康检测:数据库、Redis、表统计、更新时长、系统性能全链路监控
java·数据库·redis
5***E68526 分钟前
MySQL:drop、delete与truncate区别
数据库·mysql
记得记得就1511 小时前
【MySQL数据库管理】
数据库·mysql·oracle
Austindatabases1 小时前
给PG鸡蛋里面挑骨头--杭州PostgreSQL生态大会
数据库·postgresql
秃了也弱了。1 小时前
MySQL空间函数详解,MySQL记录经纬度并进行计算
android·数据库·mysql
星环处相逢2 小时前
MySQL数据库管理从入门到精通:全流程实操指南
数据库·mysql
h***04772 小时前
SpringBoot集成Flink-CDC,实现对数据库数据的监听
数据库·spring boot·flink
源来猿往2 小时前
redis-架构解析
数据库·redis·缓存
河南博为智能科技有限公司2 小时前
高集成度国产八串口联网服务器:工业级多设备联网解决方案
大数据·运维·服务器·数据库·人工智能·物联网
Wang's Blog2 小时前
MongoDB小课堂: 深度诊断与优化——响应时间、内存压力及连接数故障全方位解决指南
数据库·mongodb