当前位置:   article > 正文

mysql中用逗号隔开的字段作查询用(find_in_set的使用)_mysql以逗号拼接的字段如何查询

mysql以逗号拼接的字段如何查询

mysql中用逗号隔开的字段作查询用(find_in_set的使用)

场景说明

在工作中,经常会遇到一对多的关系。想要在mysql中保存这种关系,一般有两种方式,一种是建立一张中间表,这样一条id就会存在多条记录。或者采用第二种方式,直接在表中增加ids字段,将关联表的id拼接成用逗号分隔的字符串保存起来。
那么问题来了,如果采用第二种方式的话,查询的时候要如何处理呢

1. like查询方式

select * from XXX where ids like ‘%1%’
这种方式有个问题 如果表里面的id查过了10 ,那’%1%'就会把10,11,这些带1的id全都匹配处理。故like查询可能会查询出我们不想要的数据

2.FIND_IN_SET(str,strlist)

select * from XXX where find_in_set(‘1’, ids)
查询效果:
查询所有数据:

通过find_in_set过滤
可以看到find_in_set(‘2’, difficulty_type)将difficulty_type中包含2这个id的数据过滤出来了,且不会过滤出21,22这种数据

3.mybaits中使用

   <select id="queryList" parameterType="java.util.Map" resultType="com.zfkj.demo.entity.SjExampaperRule">
       SELECT * FROM `sj_exampaper_rule`
        where 1=1
        <if test="ruleName!=null and ruleName!=''">
            and rule_name like concat('%', #{ruleName}, '%')
        </if>
        <if test="bankId!=null">
            and bank_id = #{bankId}
        </if>
       <if test="trainLevels!=null">
            <foreach collection="trainLevels" item="trainLevel" open=" and (" close=")" index="index" separator=" or ">
                find_in_set (#{trainLevel},train_level)
            </foreach>
       </if>
       <if test="difficultyTypes!=null">
           <foreach collection="difficultyTypes" item="difficultyType" open=" and (" close=")" index="index" separator=" or ">
               find_in_set (#{difficultyType},difficulty_type)
           </foreach>
       </if>
       <if test="subjects!=null">
           <foreach collection="subjects" item="subject" open=" and (" close=")" index="index" separator=" or ">
               find_in_set (#{subject},subject)
           </foreach>
       </if>
   </select>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

效果:
在这里插入图片描述
在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/230859
推荐阅读
相关标签
  

闽ICP备14008679号