当前位置:网站首页>How to query fields separated by commas in MySQL as query criteria - find_ in_ Set() function

How to query fields separated by commas in MySQL as query criteria - find_ in_ Set() function

2022-06-23 06:11:00 Bald and weak.

Write it at the front

Use mysql when , It is possible that a field represents a set , If this set is drawn into a single table, it is not worth it , At this time, we store , You can choose to separate the data with commas ( You can only use commas in English ), As shown in the figure :
 Insert picture description here
How to check when making a query ?

As query criteria

If you give a data as a query condition , Determine whether the field exists , How should I check it ?

SELECT * FROM student where find_in_set(' Sing a song ', sign) > 0;

Use find_in_set() Functions are easy to implement , take sign The field contains ’ Sing a song ’ Attribute data , Rather than using like.
 Insert picture description here

Multi conditional queries are used for mybatis

If you want to query multiple conditions , For example, both Sing a song 、 Again in line with dance Of , You can write like this :

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

Aggregate query count total

How to calculate the total ?

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

 Insert picture description here
The length of the original field contents - The length of the contents after deleting the comma = How many commas are in this field ;

However, the last one is without commas, so +1

Inquire about distinct A list of

There is no better way , Only first distinct sign This field , Find out , Then use the program to judge one by one ...

原网站

版权声明
本文为[Bald and weak.]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206230433016010.html