mysql GROUP_CONCAT() 与 find_in_set() 的使用

5 篇文章 0 订阅

mysql GROUP_CONCAT() 与 find_in_set() 的使用

GROUP_CONCAT() 函数 , 多与 group by 连用

https://blog.csdn.net/u012620150/article/details/81945004

find_in_set() 函数
https://www.fujieace.com/mysql/functions/find_in_set.html

项目中的应用 场景 sys_user, 用户表, sys_role_user 用户角色中间表.
一个用户会有多个角色, 现需在用户分页查询sql中,进行用户角色的筛选,
如果用联查, 则一个用户有多个角色的时候会查出多条重复数据,
现使用

(select GROUP_CONCAT(t3.role_id) from sys_role_user t3 where t3.user_id=t1.id) roleids

将用户的所有角色放置到一个字段中;
然后使用

 where find_in_set(#{roleId}, t.roleids);

进行条件过滤, 注意 表 t 的存在

        select t.* from (select t1.*,
        (select t2.name from sys_dept t2 where t2.id=t1.dept_id) deptName,
        (select GROUP_CONCAT(t3.role_id) from sys_role_user t3 where t3.user_id=t1.id) roleids
        from sys_user t1
        where t1.del_flag = 0
        and t1.super_admin = 0
        and t1.super_tenant = 0
        and t1.tenant_code = #{tenantCode}
        <if test="username != null and username.trim() != ''">
            and t1.username like #{username}
        </if>
        <if test="deptId != null and deptId.trim() != ''">
            and t1.dept_id = #{deptId}
        </if>
        <if test="gender != null and gender.trim() != ''">
            and t1.gender = #{gender}
        </if>
        <if test="mobile != null and mobile.trim() != ''">
            and t1.mobile = #{mobile}
        </if>
        <if test="realName != null and realName.trim() != ''">
            and t1.realName = #{real_name}
        </if>
        <if test="deptIdList != null">
            and t1.dept_id in
            <foreach item="id" collection="deptIdList" open="(" separator="," close=")">
                #{id}
            </foreach>
        </if> ) t
        <if test="roleId != null and roleId.trim() != ''">
            where find_in_set(#{roleId}, t.roleids);
        </if>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值