Application of mysql SUBSTRING_INDEX in business scenarios

business problem

In the education industry, when arranging classes, it is necessary to merge similar classes with a small number of people.

After the merger, when counting the current number of people in the class, it is necessary to add the current number of people in the associated class of the combined class as the combined number of the combined class.

So how to realize the calculation of the number of people in the class through code?

Assume that the current table structure is as follows (the number of people in the class is the target value)

shift number current number Combined classes Number of people in the group
A 1 A,B,C 6
B 2 A.B 3
C 3 B,C 5
D 10 D 10

Solutions

1. Split the existing combined class associated class
2. Match the current number of students involved in the associated class of the combined class
3. Add the current number of people

Involving technical knowledge points

1. MYSQL splits the field function according to the fixed identifier [SUBSTRING_INDEX(str, delim, count)]
str: the string to be processed
delim: separator
count: if the count is positive, count from the left; if it is negative, then count from right


2. Mysql built-in table (mysql's built-in table help_topic_id)
mysql's built-in table help_topic_id contains 508 pieces of data (the number of data pieces is different in different versions), and the user needs to have the permission to query the table. In this case, only the segmentation is satisfied
. The number of strings is less than 508, otherwise you should customize the auxiliary table and set a larger incremental column

 

core code

/*核心表*/
CREATE TABLE `test_classnum` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `classcode` varchar(255) DEFAULT NULL,
  `num` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `test_change` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `text` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

/*核心SQL*/
select  allmessage.原始班号 as 班号,allmessage.全部关联班级 as 合班关联班级,sum(allmessage.合班人数) as 合班人数 from
/*关联合班班级,匹配合班人数*/
(SELECT listClassCode.name as 原始班号 , listClassCode.text as 全部关联班级,  listClassCode.关联班级 as 关联班级,
test_classnum.num as 合班人数
from
/*
按照,分割班号
*/
(SELECT t.name ,t.text ,substring_index(substring_index(t.text,',', b.help_topic_id + 1), ',', -1) as 关联班级
FROM test_change t join mysql.help_topic b ON b.help_topic_id <  (LENGTH(t.text) - LENGTH(REPLACE(t.text, ',', '')) + 1)) as listClassCode,
test_classnum  WHERE listClassCode.关联班级 = test_classnum.classcode ) as allmessage
GROUP BY allmessage.原始班号,allmessage.全部关联班级

 

Guess you like

Origin blog.csdn.net/weixin_41160534/article/details/103033897
Recommended