mysql對以逗號分隔的字段內容進行查詢
find_in_set函數(shù)
背景
使用mysql時,有可能一個字段代表一個集合,如果將這個集合單獨抽成一張表又不值當?shù)模@個時候我們存儲時,可以選擇用逗號將數(shù)據(jù)分隔開(只能用英文的逗號),如圖所示:
做查詢時怎么查呢?
單條件查詢
假如說給一個數(shù)據(jù)作為查詢條件,判斷該字段是否存在,應該怎么查呢?
SELECT * FROM student where find_in_set('唱歌', sign) > 0;
使用find_in_set()函數(shù)輕松實現(xiàn),將sign字段中含有’唱歌’屬性的數(shù)據(jù)查詢出來,而不是用like。
多條件查詢用于mybatis
1、多個條件查詢,比如:既符合 唱歌 、又符合 跳舞 的,就可以這樣寫:
<if test="list!= null and list.size() > 0">
<foreach item="item" index="index" collection="sign.split(',')">
AND find_in_set(#{item} , sign) > 0
</foreach>
</if>
2、多個條件查詢,比如:符合 唱歌 、或者符合 跳舞 的,就可以這樣寫:
第一種:
<if test="list!= null and list.size() > 0">
<trim prefix="and (" prefixOverrides="AND|OR" suffix=")">
<foreach collection="list" item="item">
OR find_in_set(#{item} , sign) > 0
</foreach>
</trim>
</if>
第二種:
<if test="list!= null and list.size() > 0">
and
<foreach item="item" index="index" collection="list open="(" separator="or" close=")">
find_in_set(#{item} , sign) > 0
</foreach>
</if>
聚合查詢count總數(shù)
怎么計算總數(shù)呢?
SELECT sum(LENGTH(sign) - LENGTH(REPLACE(sign,',','')) + 1) count FROM student;
注:原始字段內容的長度 - 把逗號進行刪除后的內容長度 = 該字段中有多少個逗號;然而最后一位是不帶逗號的所以要+1。
查詢distinct的列表
沒有什么更好的辦法,只能先distinct sign這個字段,查詢出來,然后使用程序挨個判斷了。。。
find_in_set()函數(shù)走索引嗎
我們使用執(zhí)行計劃看一下(這里將sign字段設置為了索引)
locate函數(shù)
一個字段以逗號相隔,當查詢的時候,入?yún)⑼菃蝹€或者集合(單個使用like或find_in_set)而list時可以采用以下方法:
select count(*) from engine_temp_variable where del_flag =0 and
<if test="list!= null and list.size() > 0">
<trim prefix="and (" prefixOverrides="AND|OR" suffix=")">
<foreach collection="list" item="id">
or (locate(concat(#{id},','),variableFieldIds) > 0 )
</foreach>
</trim>
</if>
擴展:
1、locate(substr,str):返回字符串substr中第一次出現(xiàn)子字符串的位置 str,沒有出現(xiàn)返回0。
2、concat(str1, str2,…):將多個字符串拼接為一個,如果有任何一個參數(shù)為null,則返回值為null。
position函數(shù)
POSITION(substr IN str)
其中substr表示要查找的字符串,str表示被查找的字符串。
因為in標識包含,意為:根據(jù)str這個條件,篩選substr符合的數(shù)據(jù)
例:
select user_name from sys_user where POSITION(user_name in 'cyadmin')
若是關聯(lián)表數(shù)據(jù)量過大時,可以判斷l(xiāng)eft join 傳參
例:
<if test="userId != null and userId != 0"> left join sys_user su on su.user_id = #{userId} and POSITION(r.park_code in su.parks)</if>
入?yún)⑹莑ist,查詢文章來源:http://www.zghlxwxcb.cn/news/detail-485309.html
<if test="params.spaceTypesList != null and params.spaceTypesList.size() >0">
and
<foreach collection="params.spaceTypesList" item="spaceTypesItem" index="index" open="(" close=")"
separator="or">
POSITION(#{spaceTypesItem} IN space_types)
</foreach>
</if>
參考鏈接:find_in_set()函數(shù)文章來源地址http://www.zghlxwxcb.cn/news/detail-485309.html
到了這里,關于mysql對以逗號分隔的字段內容進行查詢——find_in_set函數(shù)或locate函數(shù)的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!