需求:人員表中有人員角色user_type字段,一個人可以有多個角色,user_type存的是以逗號分隔的字符串,現在要篩選出多個角色的人員信息
例如:現在篩選出user_type中含1和2的人員列表
方法一:
1、mysql查詢
SELECT user_name, user_type FROM user WHERE find_in_set('1', user_type) OR find_in_set('2', user_type)
2、程序裏mybatis可以這樣寫
傳參:List 類型 userTypeList:[1,2]
<select id="" parameterType="" resultMap="">
SELECT user_name,user_type
FROM user
<where>
1=1
<if test="userTypeList != null and userTypeList.size() >0">
<foreach collection="userTypeList" open="and (" close=")" item="id" separator="or">
<if test="id != null and id != '' ">
find_in_set(#{id}, user_type)
</if>
</foreach>
</if>
</where>
</select>
方法二:
1、mysql查詢
SELECT user_name, user_type FROM user WHERE 1=1 AND CONCAT(',', user_type, ',') REGEXP '(,2,)|(,1,)'
(,2,)作爲一個整體查詢,這樣處理是因爲REGEXP不能根據逗號 分隔篩選,會查出來所有帶2的角色,如:21
2、程序裏寫法
傳參:String類型 userType: “1,2”
<select id="" parameterType="" resultMap="">
SELECT user_name,user_type
FROM user
<where>
1=1
<if test="userType != null and userType != '' ">
AND CONCAT(',', user_type, ',') REGEXP (CONCAT('(,', REPLACE(#{userType},',',',)|(,'), ',)'))
</if>
</where>
</select>