iis服务器助手广告广告
返回顶部
首页 > 资讯 > 数据库 >mysql中用逗号隔开的字段作查询用(find_in_set的使用)
  • 283
分享到

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

mysql数据库 2023-10-25 21:10:23 283人浏览 安东尼
摘要

Mysql中用逗号隔开的字段作查询用(find_in_set的使用) 场景说明 在工作中,经常会遇到一对多的关系。想要在mysql中保存这种关系,一般有两种方式,一种是建立一张中间表,这样一条id就会

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>

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

来源地址:https://blog.csdn.net/qq_29660549/article/details/129244821

您可能感兴趣的文档:

--结束END--

本文标题: mysql中用逗号隔开的字段作查询用(find_in_set的使用)

本文链接: https://www.lsjlt.com/news/442890.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作