赞
踩
在工作中,经常会遇到一对多的关系。想要在mysql中保存这种关系,一般有两种方式,一种是建立一张中间表,这样一条id就会存在多条记录。或者采用第二种方式,直接在表中增加ids字段,将关联表的id拼接成用逗号分隔的字符串保存起来。
那么问题来了,如果采用第二种方式的话,查询的时候要如何处理呢
select * from XXX where ids like ‘%1%’
这种方式有个问题 如果表里面的id查过了10 ,那’%1%'就会把10,11,这些带1的id全都匹配处理。故like查询可能会查询出我们不想要的数据
select * from XXX where find_in_set(‘1’, ids)
查询效果:
可以看到find_in_set(‘2’, difficulty_type)将difficulty_type中包含2这个id的数据过滤出来了,且不会过滤出21,22这种数据
<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>
效果:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。