mysql对以逗号分隔的字段内容进行查询——find_in_set函数或locate函数

mysql对以逗号分隔的字段内容进行查询

find_in_set函数

背景

使用mysql时,有可能一个字段代表一个集合,如果将这个集合单独抽成一张表又不值当的,这个时候我们存储时,可以选择用逗号将数据分隔开(只能用英文的逗号),如图所示:
表
做查询时怎么查呢?

单条件查询

假如说给一个数据作为查询条件,判断该字段是否存在,应该怎么查呢?

SELECT * FROM student where find_in_set('唱歌', sign) > 0;

使用find_in_set()函数轻松实现,将sign字段中含有’唱歌’属性的数据查询出来,而不是用like。
查询结果

多条件查询用于mybatis

1、多个条件查询,比如:既符合 唱歌 、又符合 跳舞 的,就可以这样写:

<if test="sign != null and sign != ''">
    <foreach item="item" index="index" collection="sign.split(',')">
        AND find_in_set(#{
    
    item} , sign) > 0
    </foreach>
</if>

2、多个条件查询,比如:符合 唱歌 、或者符合 跳舞 的,就可以这样写:

<if test="list!= null and list != ''">
    (
    <trim prefixOverrides="AND|OR">
        <foreach collection="list" item="item">
            OR find_in_set(#{
    
    item} , sign) > 0
        </foreach>
    </trim>
    )
</if>

聚合查询count总数

怎么计算总数呢?

SELECT sum(LENGTH(sign) - LENGTH(REPLACE(sign,',','')) + 1) count FROM student;

结果
注:原始字段内容的长度 - 把逗号进行删除后的内容长度 = 该字段中有多少个逗号;然而最后一位是不带逗号的所以要+1。

查询distinct的列表

没有什么更好的办法,只能先distinct sign这个字段,查询出来,然后使用程序挨个判断了。。。

find_in_set()函数走索引吗

我们使用执行计划看一下(这里将sign字段设置为了索引)

索引测试

locate函数

一个字段以逗号相隔,当查询的时候,入参往往是单个或者集合(单个使用like或find_in_set)而list时可以采用以下方法:

select count(*) from engine_temp_variable where del_flag =0 and
<if test="list != null ">
    (
    <trim prefixOverrides="AND|OR">
        <foreach collection="list" item="id">
            or (locate(concat(#{
    
    id},','),variableFieldIds) > 0 )
        </foreach>
    </trim>
    )
</if>

扩展:
1、locate(substr,str):返回字符串substr中第一次出现子字符串的位置 str,没有出现返回0。
2、concat(str1, str2,…):将多个字符串拼接为一个,如果有任何一个参数为null,则返回值为null。

参考链接:find_in_set()函数

猜你喜欢

转载自blog.csdn.net/qq_42547733/article/details/129010183
今日推荐