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>

更新:
上述语句出现了bug,本来相查询id为17的值,但是顺带着7也出来了
在这里插入图片描述

解决方法:

SELECT * FROM action WHERE INSTR(CONCAT(',',17,','),CONCAT(',',act_id,','))

方法来源于该片博客:mysql使用instr达到in(字符串)的效果

意外发现

SELECT * FROM action WHERE INSTR(CONCAT(act_id),CONCAT(17));

将id字段和字符串互换位置后,这个问题好像 解决了
在这里插入图片描述

但是在这种情况下
在这里插入图片描述
查询出现问题!!!所以行不通
查询INSTR()的用法,有所明悟:

INSTR(STR,SUBSTR) 在一个字符串(STR)中搜索指定的字符(SUBSTR),返回发现指定的字符的位置(INDEX);
STR 被搜索的字符串
SUBSTR 希望搜索的字符串
在字符串STR里面,字符串SUBSTR出现的第一个位置(INDEX),INDEX是从1开始计算,如果没有找到就直接返回0,没有返回负数的情况。

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

原文地址:https://www.cnblogs.com/sunqiangstyle/p/10312301.html