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)
            )
相关推荐
笨小孩@GF 知行合一8 小时前
易语言-高级应用
数据库·编程·易语言·中文编程
KaiwuDB9 小时前
KaiwuDB 运维实战04:DRBD + KaiwuDB——物联网场景下的低成本数据库高可用方案
运维·数据库·物联网·时序数据库·kaiwudb·aiot·多模数据库
夜雪一千11 小时前
MySQL外键彻底入门:是什么、怎么用、什么时候不该用
数据库·mysql
qq_3344668611 小时前
删除SSMS的历史登录记录
数据库·sql
zl_dfq11 小时前
Redis 之 【常见面试题总结】(从数据类型到高可用、缓存一致性全解析)
数据库·redis
龙亘川11 小时前
铭记英烈守初心,数字强基促服务:亘川智城退役军人服务系统的实践与价值
java·数据库·人工智能
kv11012 小时前
Android studio国内开发有关
java·数据库·android studio
哭泣方源炼蛊12 小时前
正则表达式c++内容汇集
数据库·c++·mysql·正则表达式
余槐i13 小时前
EXPLAIN 显示走了索引查询仍慢:回表与选择性在 500 万行表上拉开 10 倍耗时
数据库·postgresql·性能优化·vacuum·explain