mysql外键是多个id组成的字符串,查询方法
借鉴:mysql使用instr达到in(字符串)的效果
结论:select * from 表名where INSTR(CONCAT(字符串),CONCAT(表id))
问题来源:一表中的某字段是另一表的外键,该字段是外键表的id组成的字符串,如“1,2,3,4”这种形式,如何关联查询两张表,根据外键id查询另一张表呢?
表一:
表二:
首先想到的思路,对字符串进行遍历查询,但是mybatis中collection不接受string,所以我没有实现这个思路。
<foreach collection="act_id.split(',')" open="(" separator="," close=")" item="item" >
#{item}
</foreach>
第二个思路,使用concat进行字符串拼接,如“1,2,3,4”转化为(“1,2,3,4”),但是mysql where in 后不可以使用字符串,无法识别,这个思路也没有实现。
第三个思路,使用instr达到in(字符串)的效果
instr函数不懂,instr(str,substr)
与instr(substr,str)
效果截然不同,但是利用select * from 表名where INSTR(CONCAT(字符串),CONCAT(表id))
实现了需求,mybatis中mapper如下:
<!--Action结果映射-->
<resultMap id="ActionMapper" type="Action">
<id column="act_id" property="actId"/>
<result column="act_name" property="actName"/>
<result column="machine" property="machine"/>
<result column="count_time" property="countTime"/>
<result column="count_class_id" property="countClassId"/>
<result column="strength_id" property="strengthId"/>
</resultMap>
<select id="getAction" resultMap="ActionMapper">
SELECT * FROM action WHERE INSTR(CONCAT(#{xx}),CONCAT(act_id));
</select>
<!--CoursePlan结果映射-->
<resultMap id="CoursePlanMapper" type="CoursePlan">
<id column="id" property="id"/>
<result column="plan_name" property="planName"/>
<result column="plan_class_id" property="planClassId"/>
<collection column="act_id" property="action" select="getAction"/>
</resultMap>
<insert id="add" parameterType="CoursePlan" >
insert into course_plan (plan_name,plan_class_id,act_id)
-- CONCAT_WS进行字符串拼接,以,为分隔符
values (#{planName},#{planClassId},CONCAT_WS(',',<foreach collection="action" item="actid" open="" close="" separator=",">#{actid.actId}</foreach>))
</insert>
<select id="getone" parameterType="_int" resultMap="CoursePlanMapper">
select * from course_plan where id= #{id}
</select>
<select id="list" resultMap="CoursePlanMapper">
select * from course_plan
</select>
</mapper>