济南天桥区网站建设公司,长春微信网站建设,东莞网站建设58,国内自建站mysql中用逗号隔开的字段作查询用(find_in_set的使用)
场景说明
在工作中#xff0c;经常会遇到一对多的关系。想要在mysql中保存这种关系#xff0c;一般有两种方式#xff0c;一种是建立一张中间表#xff0c;这样一条id就会存在多条记录。或者采用第二种方式#xff…mysql中用逗号隔开的字段作查询用(find_in_set的使用)
场景说明
在工作中经常会遇到一对多的关系。想要在mysql中保存这种关系一般有两种方式一种是建立一张中间表这样一条id就会存在多条记录。或者采用第二种方式直接在表中增加ids字段将关联表的id拼接成用逗号分隔的字符串保存起来。 那么问题来了如果采用第二种方式的话查询的时候要如何处理呢
1. like查询方式
select * from XXX where ids like ‘%1%’ 这种方式有个问题 如果表里面的id查过了10 那’%1%就会把1011,这些带1的id全都匹配处理。故like查询可能会查询出我们不想要的数据
2.FIND_IN_SET(str,strlist)
select * from XXX where find_in_set(‘1’, ids) 查询效果 可以看到find_in_set(‘2’, difficulty_type)将difficulty_type中包含2这个id的数据过滤出来了且不会过滤出2122这种数据
3.mybaits中使用 select idqueryList parameterTypejava.util.Map resultTypecom.zfkj.demo.entity.SjExampaperRuleSELECT * FROM sj_exampaper_rulewhere 11if testruleName!null and ruleName!and rule_name like concat(%, #{ruleName}, %)/ifif testbankId!nulland bank_id #{bankId}/ifif testtrainLevels!nullforeach collectiontrainLevels itemtrainLevel open and ( close) indexindex separator or find_in_set (#{trainLevel},train_level)/foreach/ifif testdifficultyTypes!nullforeach collectiondifficultyTypes itemdifficultyType open and ( close) indexindex separator or find_in_set (#{difficultyType},difficulty_type)/foreach/ifif testsubjects!nullforeach collectionsubjects itemsubject open and ( close) indexindex separator or find_in_set (#{subject},subject)/foreach/if/select效果