1. 程式人生 > >mysql表單一欄位是多個id組成的字串,查詢方法

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>